Lake Counting
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 17917 Accepted: 9069
Description
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
Input
Line 1: Two space-separated integers: N and M
Lines 2..N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
Output
Line 1: The number of ponds in Farmer John’s field.
Sample Input
10 12
W……..WW.
.WWW…..WWW
….WW…WW.
………WW.
………W..
..W……W..
.W.W…..WW.
W.W.W…..W.
.W.W……W.
..W…….W.
Sample Output
3
思路
从任意的W开始,不停地把邻接的部分用’.’代替。 1次DFS后与初始的这个W连接的所有W就都被替
换成了’.’,因此直到图中不再存在W为止,总共进行DFS的次数就是答案了。 8个方向共对应了8种
状态转移,每个格子作为DFS的参数至多被调用一次,所以复杂度为O(8×N×M)=O(N×M)。
#include<stdio.h>#define MAX_N 105#define MAX_M 105char field[MAX_N][MAX_M];int N,M;void dfs(int x,int y){ int dx,dy,nx,ny; field[x][y] = '.'; //将现在位置替换为'.'; for (dx = -1;dx < 2;dx++) //遍历移动的8个方向 { for (dy = -1;dy < 2;dy++) { nx = x + dx,ny = y + dy; if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W') { //判断(nx,ny)是不是在园子内 dfs(nx,ny); } } }}int main(){ int i,j,res = 0; char tmp; scanf("%d%d",&N,&M); getchar(); for (i=0;i<N;i++) { for (j=0;j<M;j++) { scanf("%c",&field[i][j]); if (j==M-1) { scanf("%c",&tmp); } } } for (i = 0;i < N;i++) { for (j = 0;j < M;j++) { if (field[i][j] == 'W') { dfs(i,j); res++; } } } printf("%d\n",res); return 0;}