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

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

代码如下:   

 

 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 }

 

转载于:https://www.cnblogs.com/huangguodong/p/4669638.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值