poj2386 Lake Counting DFS

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.

題意:大小爲N*M的園子下雨積水,八連通的積水被認爲是連接在一起的,請問園子裏一共有多少水窪。

題解:題目要求的就是W一共有多少塊。找到一個W就開始DFS,然後將其變爲'.'。搜索八個方向就可以了。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
char a[101][101];
int  n,m;
void dfs(int x,int y)
{
    a[x][y]='.';
    for(int i=-1;i<=1;i++)
        for(int j=-1;j<=1;j++)
    {
        int nx=x+i;
        int ny=y+j;
        if(nx>0&&ny>0&&nx<=n&&ny<=m&&a[nx][ny]=='W')
        {
            dfs(nx,ny);
        }
    }
    return ;
}
int main()
{
    int ans;
    while(cin>>n>>m)
    {
        ans=0;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
                cin>>a[i][j];
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
        {
            if(a[i][j]=='W')
            {
                dfs(i,j);
                ans++;
            }
        }
        cout<<ans<<endl;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章