种子填充找连通块 floodfill
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.
题目意思:输入行数列数,m,n。然后输入像上面的字符。找连着的W有多少块.....
解题思路:首先用一个二维字符数组把输入的存起来.... 然后一个一个的循环,如果是W并且还没有被标记过就进入zhao这个函数
zhao函数:找嘛,大概意思就是,看当前位置的8个方向有没有连通的,这里用到了递归。希望代码上的注释,对你有帮助。
(其实,自己对这代码的意思也是似懂非懂,找书打出来的)
代码如下:
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 const int maxn=1000; 5 int m,n; //这里将m,n定义在主函数外,作为全局变量,好被zhao函数调用 6 char s[maxn][maxn]; 7 int d[maxn][maxn]; 8 void zhao(int r,int c,int b) 9 { 10 if(r<0||r>=m||c<0||c>=n) //出界的,不要 11 return; 12 if(d[r][c]>0||s[r][c]!='W') // 不是W,或者已经访问标记过了的格子 13 return; 14 d[r][c]=b; //给访问过的格子标记 15 for(int dr=-1;dr<=1;dr++) //这两个循环是表示一个格子的八个方向 16 { 17 for(int dc=-1;dc<=1;dc++) 18 if(dr!=0||dc!=0) //这里不要0,0的格子,因为这就是它本身,并没有动 19 zhao(r+dr,c+dc,b); //递归,将dr,dc加上去,这样就寻找了附近的格子 20 } 21 } 22 23 int main() 24 { 25 26 memset(d,0,sizeof(d)); //将d数组清零,好标记 27 while(cin>>m>>n) 28 { 29 int flag=0; 30 for(int i=0; i<m; i++) 31 { 32 for(int j=0; j<n; j++) 33 cin>>s[i][j]; 34 } 35 for(int i=0; i<m; i++) 36 { 37 for(int j=0; j<n; j++) 38 { 39 if(d[i][j]==0&&s[i][j]=='W') 40 zhao(i,j,++flag); 41 } 42 } 43 cout<<flag<<endl; 44 } 45 return 0; 46 }