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.
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.
* 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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
解题思路:
此题与二叉树遍历类似,图也有DFS和BFS遍历,这个问题用的是DFS找连通块:从每个"W“格子出发,递归遍历它周围的”W"格子。每次访问一个格子时就给它写上一个“连通分量编号”即下面代码的q数组“,这样就可以在访问之前检查它是否已经有了编号,从而避免同一个格子重复访问。
下面代码是用一个二重循环来找到当前格子的相邻8个格子,也可以用常量数组或者写8条调用语句,
程序代码:
#include <cstdio> #include <cstring> using namespace std; const int maxn=100+5; char p[maxn][maxn]; int m,n,q[maxn][maxn]; void fld(int i,int j,int w) { if(i<0||i>=m||j<0||j>=n) return ; if(q[i][j]>0||p[i][j]!='W') return; q[i][j]=w; for(int r=-1;r<=1;r++) for(int c=-1;c<=1;c++) if(c==0&&r==0) continue; else fld(r+i,j+c,w); } int main() { while(scanf("%d%d",&m,&n)==2&&m&&n) { for(int i=0;i<m;i++) scanf("%s",p[i]); memset(q,0,sizeof(q)); int cf=0; for(int i=0;i<m;i++) for(int j=0;j<n;j++) if(q[i][j]==0&&p[i][j]=='W') fld(i,j,++cf); printf("%d ",cf); } return 0; }