【题解】POJ 2386 LakeCounting(DFS)

这篇博客介绍了如何使用深度优先搜索(DFS)解决POJ 2386 LakeCounting的问题。题目要求计算一块N x M的农场中,由'W'表示的积水区域形成的池塘数量。给定农场的布局后,通过DFS算法找出所有连通的积水区域并计数。博客内容包括问题描述、输入输出格式以及问题解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POJ 2386 LakeCounting


原题

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.

https://vjudge.net/problem/POJ-2386

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

题意

因为下雨农场里有许多积水,连接在一起的积水为一个池塘,问一共有几片池塘。
’W’为有积水的土地,’.'为干燥的土地,这是一道基础的dfs题。
输入:第一行是农场的宽N和长M。(1 <= N, M <= 100)
接下来N+1行为每一行的土地情况,每行有M个字符分别为’W’,’.’。
输出:池塘的个数。
直接上代码


#include<iostream>
using namespace std;

char field[101][101];
int n, m, sum = 0;
void dfs(int x, int y)
{
	field[x][y] = '.';	//每找到一个'W'就把它标记为'.'
	for(int i = x - 1; i <= x + 1; i++)//该点周围一圈是否有积水
		for(int j = y - 1; j <= y + 1; j++)
			if(x >= 0 && x < n && y >= 0 && y < m && field[i][j] == 'W')
				dfs(i,j);
}
int main()
{
	cin >> n >> m;
	for(int i = 0; i < n; i++)
		for(int j = 0; j < m; j++)
			cin >> field[i][j];
	for(int i = 0; i < n; i++)
		for(int j = 0; j < m; j++)
			if(field[i][j] == 'W'){
				dfs(i,j);sum++;//每找到一个'W'都会把它自己以及与它相连的所有'W'都标记为'.'
			}					//所以直接用sum记录即可
	cout << sum << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值