DFS求连通块(漫水填充法)

G - DFS(floodfill),推荐
Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status

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


其实这道题和UVA 572是一样的,甚至代码都不需要怎么改~~~~
漫水填充,其实就是赋值了,一个连通块赋同一个值,填充完之后答案也就出来咯
例如样例输入中的填充完就是这样:

100000000220
011100000222
000011000220
000000000220
000000000200
003000000200
030300000220
303030000020
030300000020
003000000020

 

 

#include"iostream"
#include"cstring"
#include"cstdio"
using namespace std;

char a[101][101];
int book[101][101];
int n,m;

void dfs(int x,int y,int z)
{
if(x<0||x>=n||y<0||y>=m)
        return;
if(book[x][y]>0||a[x][y]!='W')
        return;
book[x][y]=z;
for(int i=-1;i<=1;i++)
for(int j=-1;j<=1;j++)
if(j!=0||i!=0) dfs(x+i,y+j,z);
}

int main()
{
    while(scanf("%d%d",&n,&m)==2&&n&&m)
    {
   //  memset(a,0,sizeof(a));
     for(int i=0;i<n;i++) scanf("%s",a[i]);
     memset(book,0,sizeof(book));
     int ans=0;
     for(int j=0;j<n;j++)
     for(int k=0;k<m;k++)
     {
        if(book[j][k]==0&&a[j][k]=='W') {dfs(j,k,++ans);}
     }
cout<<ans<<endl;
    }
    return 0;
}


posted @ 2015-07-21 15:00  江南何采莲  阅读(274)  评论(0编辑  收藏  举报