B - DFS/BFS POJ - 2386

B - DFS/BFS

 POJ - 2386 

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

题目描述:

数出农田里面水洼,w为水洼,.为陆地,w周围8格内若有水洼,这这些水洼是连通的,只算做一个。

分析:

白书模板题。用dfs来查找8格内的水洼,找到则再dfs查找该水洼周围8格是否还有连通。每连通在一起的大水洼记为1个。

代码:

#include<stdio.h> 
char a[103][103];
int N,M;
int dfs(int y,int x)
{   
    a[y][x]='B';
    if(y<0||y>=N||x<0||x>=M) return 0;
    for(int dy=-1;dy<=1;dy++)
    {
        for(int dx=-1;dx<=1;dx++)
        {
            
            if(a[y+dy][x+dx]=='W') 
            {
                dfs(y+dy,x+dx);
            }
        }
     }  
    return 0;
    
}
​
int main()
{   
    int res=0;
    scanf("%d %d",&N,&M);
    getchar();
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<M;j++)
        {
            a[i][j]=getchar();
        }
        getchar();
    }
    for(int i=0;i<N;i++)
    {
        for(int j=0;j<M;j++)
        if(a[i][j]=='W')
        {
            dfs(i,j);
            res++;
        }
    }
    printf("%d\n",res);
    return 0;
}

 


 

posted on 2020-01-13 00:47  Aminers  阅读(110)  评论(0编辑  收藏  举报

导航