NoiOpenJudge 2.5 Lake Counting

描述
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.
輸入
* 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.
    輸出
  • Line 1: The number of ponds in Farmer John’s field.
    樣例輸入
    10 12
    W……..WW.
    .WWW…..WWW
    ….WW…WW.
    ………WW.
    ………W..
    ..W……W..
    .W.W…..WW.
    W.W.W…..W.
    .W.W……W.
    ..W…….W.
    樣例輸出
    3
    提示
    OUTPUT DETAILS:

There are three ponds: one in the upper left, one in the lower left,and one along the right side.
來源
USACO 2004 November

#include <iostream>
#include <memory.h>
using namespace std;
int n,m,a[1005][1005],dx[8]={0,0,1,-1,1,-1,-1,1},dy[8]={1,-1,0,0,1,1,-1,-1};
void dfs(int x,int y)
{
    int i,tx,ty;
    for(i=0;i<=7;i++)
    {
        tx=dx[i]+x;
        ty=dy[i]+y;
        if(tx>0&&tx<=n&&ty>0&&ty<=m&&a[tx][ty]==0)
        {
            a[tx][ty]=1;
            dfs(tx,ty);
        }
    }
}
int main()
{
    int x,y,i,j;
    long lake;
    char c;
    cin>>n>>m;
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
        {
            cin>>c;
            if(c=='W')
              a[i][j]=0;
            else if(c=='.')
                    a[i][j]=1;
        }
    lake=0;
    for(i=1;i<=n;i++)
        for(j=1;j<=m;j++)
        if(a[i][j]==0)
        {

            lake++;
            dfs(i,j);
        }
    cout<<lake<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章