POJ No.2386 Lack Counting

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40530943/article/details/81072121

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

描述

由于最近的降雨,水汇集在Farmer John's田地的不同地方,其由N×M(1 <= N <= 100; 1 <= M <= 100)的正方形矩形表示。每个方格包含水('W')或旱地('。')。农民约翰想弄清楚他的田地里有多少个池塘。池塘是一组连接的正方形,其中有水,其中一个正方形被认为与其所有八个邻居相邻。 

给出农夫约翰的田地图,确定他有多少池塘。

#include<iostream>
#define MAX_N 100
#define MAX_M 100 
using namespace std;
int N,M;
char field[MAX_N][MAX_M+1];
int dfs(int x,int y)
{
	field[x][y]='.';
	for(int dx=-1;dx<=1;dx++)
	{
		for(int dy=-1;dy<=1;dy++)
		{
			int nx=x+dx,ny=y+dy;
			if(0<=nx&&nx<=N&&ny>=0&&ny<=M&&field[nx][ny]=='W')
				dfs(nx,ny);
		}
	}
}
void solve()
{
	int res=0;
	for(int i=0;i<N;i++)
	{
		for(int j=0;j<M;j++)
		{
			if(field[i][j]=='W')
			{
				dfs(i,j);
				res++;
			}
		}
	}
	cout<<res;
}
int main()
{
	cin>>N>>M;
	for(int i=0;i<N;i++)
	{
		cin>>field[i];
	}
	solve();
}

猜你喜欢

转载自blog.csdn.net/qq_40530943/article/details/81072121
今日推荐