首页 > 其他 > 详细

POJ-2386(深广搜基础)

时间:2015-12-05 12:47:33      阅读:192      评论:0      收藏:0      [点我收藏+]
Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25322   Accepted: 12759

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

思路:
很基础的一道题目,适合拿来练手,dfs和bfs都可以
一开始还理解错题目意思了,以为只有至少两个点连着的W才算是pool,结果发现并不是,说白了这题就是让你求图中并查集的个数
理论上应该也可以用并查集做吧,然后分别写出dfs和bfs的解法

dfs:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

int n,m;
char G[107][107];
int vis[107][107];
int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};

void dfs(int x,int y)
{
    for(int i = 0;i < 8;i++)
    {
        int dx = x+dir[i][0];
        int dy = y+dir[i][1];
        if(dx>=1&&dx<=n&&dy>=1&&dy<=m && G[dx][dy]==W && !vis[dx][dy]) {
            vis[dx][dy] = 1;
            dfs(dx,dy);
        }
    }
}

int main()
{
    while(cin>>n>>m)
    {
        memset(vis,0,sizeof(vis));
        int ans = 0;
        for(int i = 1;i <= n;i++)
            scanf("%s",&G[i][1]);//注意如果是从1开始计数,就要从每一行的第一位开始从缓冲区中读取数据,这个语法要注意一下,容易出错

        for(int i = 1;i <= n;i++)
            for(int j = 1;j <= m;j++) 
                if(G[i][j]==W && !vis[i][j]) {
                    vis[i][j] = 1;
                    dfs(i,j);
                    ans++;
                }
        cout<<ans<<endl;
    }
    return 0;
}
bfs:

POJ-2386(深广搜基础)

原文:http://www.cnblogs.com/immortal-worm/p/5021287.html

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