POJ - 2386

传送门

POJ 2386

题面:

Lake Counting
Time Limit: 1000MS Memory Limit: 65536K

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

翻译

   由于最近下了雨,约翰的田里各处都积了水,用长方形N x M表示(1 <= N <= 100;
1 <= M <= 100)个正方形。每个方块包含水(“W”)或陆地(“。”)。农夫约翰想弄清楚他的田地里已经形成了多少个池塘。
  池塘是一组有水的相连的正方形,其中一个正方形被认为与所有八个相邻的正方形相邻。给出约翰的田地的示意图,判断他有多少池塘。
第一行是测试用例的数量。
  对于每个测试用例,程序都必须读取从第一行开始的数字N和S,它们之间用间隔隔开。序列的编号在测试用例的第二行给出,用间隔隔开。
输入将在文件结束时结束。

输出

  对于每种情况,程序都必须在输出文件的单独行上打印结果。如果没有回答,打印0。

思路

用深度搜索从左上开始搜索附近的水坑 然后迭代 相对简单

代码

#include<iostream>
using namespace std;
char ss[101][101];//记录字符 
int gg[101][101]={0};//记录是第几个池塘
bool dd[101][101]={0}; //记录是否被search过
void search(int n,int m,int x,int y,int a)
{	
	if(dd[n][m]==1)
		return;
	dd[n][m]=1;
	if(n-1>=1&&m-1>=1&&ss[n-1][m-1]=='W'&&dd[n-1][m-1]==0)
	{
		gg[n-1][m-1]=a;
		search(n-1,m-1,x,y,a);
	}
	if(n-1>=1&&m-1>=1&&n+1<=y&&m+1<=x&&ss[n-1][m]=='W'&&dd[n-1][m]==0)
	{
		gg[n-1][m]=a;
		search(n-1,m,x,y,a);
	}
	if(n-1>=1&&m+1<=x&&ss[n-1][m+1]=='W'&&dd[n-1][m+1]==0)
	{
		gg[n-1][m+1]=a;
		search(n-1,m+1,x,y,a);
	}
	if(m-1>=1&&ss[n][m-1]=='W'&&dd[n][m-1]==0)
	{
		gg[n][m-1]=a;
		search(n,m-1,x,y,a);
	}
	if(m+1<=x&&ss[n][m+1]=='W'&&dd[n][m+1]==0)
	{
		gg[n][m+1]=a;
		search(n,m+1,x,y,a);
	}
	if(m-1>=1&&n+1<=y&&ss[n+1][m-1]=='W'&&dd[n+1][m-1]==0)
	{
		gg[n+1][m-1]=a;
		search(n+1,m-1,x,y,a);
	}
	if(n+1<=y&&ss[n+1][m]=='W'&&dd[n+1][m]==0)
	{
		gg[n+1][m]=a;
		search(n+1,m,x,y,a);
	}
	if(n+1<=y&&m+1<=x&&ss[n+1][m+1]=='W'&&dd[n+1][m+1]==0)
	{
		gg[n+1][m+1]=a;
		search(n+1,m+1,x,y,a);
	}
	return;
} 
int main()
{
	int n,m,a=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
			cin>>ss[i][j];
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(ss[i][j]=='W'&&dd[i][j]==0)
			{
				search(i,j,m,n,++a); 
			}	
		}
	}
	cout<<a<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值