It has a size of N * M garden, rain water. Communicating hydrocephalus eight it is considered to be connected together. Request a garden total number of puddles? (Eight communication means is a figure of the relative W * portion)
* * *
* W *
* * *
limitation factor:
N,M<=100
Thinking: starting from an arbitrary W, kept in place by the abutting portion, all the primary communication DFS W initial W eight this would have been replaced, it was not until the drawing no '.' '.' Until the presence of W for a total number of DFS is the answer, a total of eight directions corresponding to eight kinds of state transitions, each grid is at most as DFS parameter called once, so complexity is O (8 * N * M)
int N, M;
char field[MAX_N][MAX_M + 1] // 园子
// 现在位置(x, y)
void dfs(int x, int y)
{
// 把现在位置替换为'.'
field[x][y] = '.';
// 遍历循环8个方向
for(int dx = -1; dx <= 1; dx++)
for(int dy = -1; dy <= 1; dy++)
{
// 向x方向移动nx 向y方向移动ny 移动的结果为(nx, ny)
int nx = x + dx;
int ny = y + dy;
if(0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W') dfs(nx, ny);
}
return;
}
void solve()
{
int res = 0;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
{
if(field[i][j] == 'W'){
dfs(i, j);
res++;
}
}
printf("%d\n", res);
}