种子填充找连通块 floodfill

时间:2023-03-09 03:16:23
种子填充找连通块  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.

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

Hint

OUTPUT DETAILS:

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个方向有没有连通的,这里用到了递归。希望代码上的注释,对你有帮助。

(其实,自己对这代码的意思也是似懂非懂,找书打出来的)

代码如下:

 #include <iostream>
#include <cstring>
using namespace std;
const int maxn=;
int m,n; //这里将m,n定义在主函数外,作为全局变量,好被zhao函数调用
char s[maxn][maxn];
int d[maxn][maxn];
void zhao(int r,int c,int b)
{
if(r<||r>=m||c<||c>=n) //出界的,不要
return;
if(d[r][c]>||s[r][c]!='W') // 不是W,或者已经访问标记过了的格子
return;
d[r][c]=b; //给访问过的格子标记
for(int dr=-;dr<=;dr++) //这两个循环是表示一个格子的八个方向
{
for(int dc=-;dc<=;dc++)
if(dr!=||dc!=) //这里不要0,0的格子,因为这就是它本身,并没有动
zhao(r+dr,c+dc,b); //递归,将dr,dc加上去,这样就寻找了附近的格子
}
} int main()
{ memset(d,,sizeof(d)); //将d数组清零,好标记
while(cin>>m>>n)
{
int flag=;
for(int i=; i<m; i++)
{
for(int j=; j<n; j++)
cin>>s[i][j];
}
for(int i=; i<m; i++)
{
for(int j=; j<n; j++)
{
if(d[i][j]==&&s[i][j]=='W')
zhao(i,j,++flag);
}
}
cout<<flag<<endl;
}
return ;
}