首页 > 其他 > 详细

POJ2386——Lake Counting

时间:2021-03-26 22:57:11      阅读:30      评论:0      收藏:0      [点我收藏+]

题目来自:http://poj.org/problem?id=2386

Description

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.
 
作者解释:就是求上、下、左、右、左上、左下、右上、右下的连通块。
作者分析:dfs深搜,思路见细胞问题
#include <iostream>
#include <cstring>
using namespace std;

int idx[101][101],m,n,ans = 0;
char a[101][101];

void dfs(int x,int y,int id){
    if (x < 0 || x >= m || y < 0 || y >= n) return;
    if (idx[x][y] > 0 || a[x][y] == .) return;
    idx[x][y] = id;
    dfs(x - 1,y,id);
    dfs(x + 1,y,id);
    dfs(x,y + 1,id);
    dfs(x,y - 1,id);
    if (x <= m - 1 && y <= n - 1) dfs(x + 1,y + 1,id);
    if (x >= 1 && y >= 1)dfs(x - 1,y - 1,id);
    if (x > 0 || y > 0) dfs(x + 1,y - 1,id);
    if (x <= m - 1 && y <= n - 1)dfs(x - 1,y + 1,id);
}

int main(){
    memset(a,0,sizeof(a));
    memset(idx,0,sizeof(idx));
    cin >> m >> n;
    for (int i = 0;i < m;i++){
        cin >> a[i];
    }
    int cnt = 0;
    for (int i = 0;i < m;i++){
        for (int j = 0;j < n;j++){
            if (idx[i][j] == 0 && a[i][j] != .){
                dfs(i,j,++cnt);
            }
        }
    }
    cout << cnt; 
    return 0;
}

POJ2386——Lake Counting

原文:https://www.cnblogs.com/linyiweiblog/p/14584267.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!