首页 > 其他 > 详细

B - DFS/BFS POJ - 2386

时间:2020-01-13 09:09:31      阅读:75      评论:0      收藏:0      [点我收藏+]

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 Johns field. Each character is either W or .. The characters do not have spaces between them.

 

Output

* Line 1: The number of ponds in Farmer Johns 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;
}

 


?

 

B - DFS/BFS POJ - 2386

原文:https://www.cnblogs.com/studyshare777/p/12185437.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!