[USACO] 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.



【题目分析】

一道简单的深搜...先创建一个bool类型的数组b,是'.'就放0,是'W'就放1....统计能组成正方形的W的个数就行...

z#include<bits/stdc++.h>
bool b[101][101];
char a[101][101];
void dfs(int i,int j)
{
    if(b[i][j]!=0)
    {
        b[i][j]=0;
        if(b[i][j-1]!=0)
         dfs(i,j-1);
        if(b[i][j+1]!=0)
         dfs(i,j+1);
        if(b[i-1][j]!=0)
         dfs(i-1,j);
        if(b[i+1][j]!=0)
         dfs(i+1,j);
        if(b[i-1][j-1]!=0)
         dfs(i-1,j-1);
        if(b[i-1][j+1]!=0)
         dfs(i-1,j+1);
        if(b[i+1][j-1]!=0)
         dfs(i+1,j-1);
        if(b[i+1][j+1]!=0)
         dfs(i+1,j+1);
    }
    return ;
}
int main()
{
    int m,n,ans=0;
    scanf("%d %d\n",&m,&n);
    int i,j;
    for(i=1;i<=m;i++)
    {
      for(j=1;j<=n;j++)
      {
         scanf("%c",&a[i][j]);
         if(a[i][j]=='W')b[i][j]=1;
      }
      getchar();
    }
     
    for(i=0;i<=m;i++)
     for(j=0;j<=n;j++)
     {
         if(b[i][j])
         {
             dfs(i,j);
             ans++;
         }
     } 
    printf("%d",ans);
    return 0;
}

 

posted @ 2017-08-21 01:11  jiandanset  阅读(357)  评论(0编辑  收藏  举报