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

Subject description:

Puddles inside the farm number, w is puddles. If the land as puddles, w 8 surrounding cells, these puddles which is connected, only one counted.

analysis:

White book template title. With dfs 8 to find puddles in the grid, and then find the dfs find out whether there is around the puddles 8 grid connectivity. Large puddles each communicating together referred to as one.

Code:

#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;
}

 


 

Guess you like

Origin www.cnblogs.com/studyshare777/p/12185437.html