Lake Counting//POJ - 2386//dfs

Lake Counting//POJ - 2386//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.
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
    题意
    求有多少片水洼
    链接:http://poj.org/problem?id=2386

思路

dfs模板题。

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>

using namespace std;
char s[103][103];
int cnt=0;
int l[8]={-1,-1,0,1,1,1,0,-1};
int r[8]={0,1,1,1,0,-1,-1,-1};
void dfs(int i,int j,int judge){
    if(s[i][j]=='.') return;
    else if(s[i][j]=='W') {
        if(judge==1) cnt++;
        s[i][j]='.';
        for(int t=0;t<8;t++){
            if(i+l[t]>=0&&j+r[t]>=0)
                dfs(i+l[t],j+r[t],0);
        }
    }
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=0;i<n;i++){
        scanf("%s",s[i]);
    }
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            if(s[i][j]=='W')
                dfs(i,j,1);
        }
    }
    cout<<cnt<<endl;
    return 0;
}

注意

发布了24 篇原创文章 · 获赞 9 · 访问量 543

猜你喜欢

转载自blog.csdn.net/salty_fishman/article/details/103963458