Lake Counting POJ2386 ( dfs )

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

OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.

题目描述:N*M花园,求有少个水池,八连通的积水认为是连接在一起的。

思路:如果该点为水池,将该点’ W ‘替换为’ . ‘并深搜,每执行一次dsf,与’ W '相连的水池就全都被替换了,直到花园中不再有W,总共的dfs次数就是答案。


    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int n,m;
    char a[105][105];
    void dfs(int x,int y)
    {
        //将现在的位置替换为'.'
        a[x][y]='.';
        //循环遍历8个方向
        for(int dx = -1; dx <= 1;dx++){
            for(int dy=-1;dy<=1;dy++){
                int nx=x+dx;
                int ny=y+dy;
                //判断是否在园子里以及是否有积水
                if(nx>=0 && nx<n && ny>=0 && ny<m && a[nx][ny]=='W')dfs(nx,ny);
            }
        }
        return ;
    }
    void solve(){
        int res=0;
        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);
    }
    int main()
    {
        scanf("%d%d",&n,&m);
        getchar();
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                scanf("%c",&a[i][j]);
            }
            getchar();    //吸收换行符
        }
        solve();
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/qq_43328040/article/details/87970413