搜索--poj 2386 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.
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
Hint
OUTPUT DETAILS: 

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

代碼:

#include<stdio.h>
#include<string>
#include<string.h>
#include<iostream>
using namespace std;
char s[102][102];
void dfs(int p,int q)
{
    int ii,jj;
    if(s[p][q]=='.') return;
    s[p][q]='.';
    for(ii=-1;ii<2;ii++)
        for(jj=-1;jj<2;jj++)
        {
            if(s[p+ii][q+jj]=='W')
            {
                dfs(p+ii,q+jj);
            }
        }
}
int main()
{
    int m,n,i,j,k,sum=0;
    scanf("%d %d",&m,&n);
    getchar();
    for(i=1;i<=m;i++)
    {
        for(j=1;j<=n;j++)
        scanf("%c",&s[i][j]);
        getchar();      //第一次交題漏了
    }
    for(i=1;i<=m;i++)
        for(j=1;j<=n;j++)
        {
            if(s[i][j]=='W')
            {
                dfs(i,j);
                sum++;
            }
        }
    printf("%d\n",sum);
    return 0;
}

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