DFS/BFS

这道题目要求计算给定N x M田地中,由水('W')形成的连通池塘数量。每个水单元格与周围的八个单元格相邻。通过 DFS 或 BFS 方法遍历田地,标记已搜索过的单元格,并累计遇到的水塘数量。题目提供了输入输出格式和解题思路,接下来是对应的代码实现。
摘要由CSDN通过智能技术生成

题目:
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.

题目大意为:由于最近的降雨,在农夫约翰田地的不同地方积聚了水,用N x M(1 <= N <= 100; 1 <= M <= 100)正方形的矩形表示。每个方格包含水(‘W’)或旱地(’。’)。农夫约翰想弄清楚他的田地里形成了多少个池塘。池塘是一组相连的正方形,里面有水,其中一个正方形被认为与八个池塘相邻。给定农夫约翰的田野图,确定他有多少个池塘。

题解:我们可以先定义一个二维字符数组,等会用它来存地图;再定义一个等大的二位整型数组,用来表示是否已经收索。由题意知若水的周围八个位置只要有水就会连在一起,形成水塘。所以我们从地图第一个位置开始搜索,如果他没有水,就搜索下一个位置,如果有,就标记并计数,同时开始搜索他旁边的八个位置,如果有水,就标记,用递归来把连成水塘的都标记起来,并记录水塘的数量即可得到答案。

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>

using namespace std;

char a[100][100];
int b[100][100];
int n, m;
int ans;

void DFS(int x,int y)
{
	b[x][y]=1;
	if(x+1<n&&a[x+1][y]=='W'&&b[x+1][y]==0) DFS(x+1,y);
	if(y+1<m&&a[x][y+1]=='W'&&b[x][y+1]==0) DFS(x,y+1);
	if(y+1<m&&x+1<n&&a[x+1][y+1]=='W'&&b[x+1][y+1]==0) DFS(x+1,y+1);
	if(x-1>=0&&a[x-1][y]=='W'&&b[x-1][y]==0) DFS(x-1,y);
	if(y-1>=0&&a[x][y-1]=='W'&&b[x][y-1]==0) DFS(x,y-1);
	if(y-1>=0&&x-1>=0&&a[x-1][y-1]=='W'&&b[x-1][y-1]==0) DFS(x-1,y-1);
	if(y-1>=0&&x+1<n&&a[x+1][y-1]=='W'&&b[x+1][y-1]==0) DFS(x+1,y-1);
	if(y+1<m&&x-1>=0&&a[x-1][y+1]=='W'&&b[x-1][y+1]==0) DFS(x-1,y+1);
}

int main()
{
	cin>>n>>m;
	for(int i=0;i<n;i++)
	cin>>a[i];
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(a[i][j]=='W'&&b[i][j]==0) 
			{
				ans++;
				b[i][j]=1;
				DFS(i,j);
			}
		} 
	}
	cout<<ans;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值