深度搜索---------Lake counting

#include<iostream>
#include<cstdio>
#include<cstdlib>
#define maxn 100
char ch[maxn][maxn];
using namespace std;
int length,width;
void dfs(int x,int y)
{
    ch[x][y]='.';//记得变.,目的是使连在一块的W也变成.,只用一次dfs
    for(int dx=-1;dx<=1;dx++)//八个方位,用循环
    {
        for(int dy=-1;dy<=1;dy++)
        {
            int nx=x+dx,ny=y+dy;
            if(nx>=0&&nx<length&&ny>=0&&ny<width&&ch[nx][ny]=='W')//找W,W在一块的只用一次dfs
                dfs(nx,ny);
        }
    }
}
int main()
{
    while(cin>>length>>width)
    {
        int num=0;
        getchar();//跳空行
        for(int i=0;i<length;i++)
        {
            scanf("%s",ch[i]);//避免吸入空行
        }
        for(int i=0;i<length;i++)
        {
            for(int j=0;j<width;j++)
            {
                if(ch[i][j]=='W')
                {
                    dfs(i,j);
                    num++;
                }
            }
        }
        cout<<num<<endl;
    }
    return 0;
}

posted @ 2020-05-28 11:54  Joelin12  阅读(115)  评论(0)    收藏  举报