Lake Counting 方法2

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013624794/article/details/19283373

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

#include<iostream>
#include<string.h>
#include<stdio.h>
#include<ctype.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<math.h>
#include<vector>
#include<deque>
#include<list>
using namespace std;
int n,m,t;
char map[150][150];
int dis[8][2]= {-1,1,-1,0,-1,-1,0,1,0,-1,1,1,1,0,1,-1};
void dfs(int x,int y)
{
    int nextx,nexty;
    for(int i=0; i<8; i++)
    {
        nextx=x+dis[i][0];
        nexty=y+dis[i][1];
        if(nextx<0||nexty<0||nextx>=m||nexty>=n||map[nextx][nexty]!='W')
            continue;
        map[nextx][nexty]='.';
        dfs(nextx,nexty);
    }
}
int main()
{
    while( scanf("%d%d",&m,&n)!=EOF)
    {
        memset(map,0,sizeof(map));
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                cin>>map[i][j];
        int count=0;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
            {
                if(map[i][j]=='W')
                {
                    map[i][j]=='.';
                    dfs(i,j);
                    count++;
                }
            }
        printf("%d\n",count);
    }
    return 0;
}
展开阅读全文

没有更多推荐了,返回首页