AOJ 0118 - Property Distribution

なんでTLEなのと思って他の方のコードを見ていたところWとHの入力順序を逆に捉えていました.
それ以外は単純にDFS.蟻本の水たまり問題みたいに解ける.

#include <iostream>

const int MAX_H = 100, MAX_W = 100, v[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
std::string map[MAX_H];
int W, H;

//x,y 現在の位置 c 消す文字
void dfs(int x, int y, char c){
	map[y][x] = ' ';

	for(int i=0;i<4;i++){
		int nx = x + v[i][0], ny = y + v[i][1];
		if(nx >= 0 && nx < W && ny >= 0 && ny < H && map[ny][nx] == c)dfs(nx,ny,c);
	}
	return ;
}

int main(){
	//Input
	while(std::cin >> H >> W,W||H){
		for(int i = 0;i < H;i++){
			std::cin >> map[i];
		}
		
		//Processing
		int res = 0;
		for(int i=0;i<H;i++){
			for(int j=0;j<W;j++){
				if(map[i][j] != ' ')
					res++,dfs(j,i,map[i][j]);
			}
		}
		
		std::cout << res << std::endl;
	}
}