POJ 3620 Avoid The Lakes(DFS)

本文介绍了一道经典的洪水模拟问题——AvoidTheLakes,通过使用深度优先搜索(DFS)来解决农场中最大湖泊面积的问题。在N*M的网格中,部分格子被水淹没,需要计算这些水域形成的连通区域的最大面积。

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

Avoid The Lakes

Description

Farmer John's farm was flooded in the most recent storm, a fact only aggravated by the information that his cows are deathly afraid of water. His insurance agency will only repay him, however, an amount depending on the size of the largest "lake" on his farm.

The farm is represented as a rectangular grid with N (1 ≤ N ≤ 100) rows and M (1 ≤ M ≤ 100) columns. Each cell in the grid is either dry or submerged, and exactly K (1 ≤ K ≤ N × M) of the cells are submerged. As one would expect, a lake has a central cell to which other cells connect by sharing a long edge (not a corner). Any cell that shares a long edge with the central cell or shares a long edge with any connected cell becomes a connected cell and is part of the lake.

Input

* Line 1: Three space-separated integers: NM, and K
* Lines 2..K+1: Line i+1 describes one submerged location with two space separated integers that are its row and column: R and C

Output

* Line 1: The number of cells that the largest lake contains. 

Sample Input

3 4 5
3 2
2 2
3 1
2 3
1 1

Sample Output

4
题目大意:FJ的农场被淹了,他的农场可以被分成N * M个格子,其中有的格子有水,有的格子没水。如果两个有水的格子共用一条边的话,则说明它们是连通的,共用一个角不算连通。求连通区域的最大面积。

解题思路:DFS求连通块。每进行一次DFS,计数器加一。每次从没有被走过的点开始搜,可以将农场中有水的地方标记为-1,没有水的地方标记为0,已经搜过的地方标记为1,可以节省一个辅助数组的空间。

代码如下:

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

using namespace std;

const int maxn = 105;
const int maxm = 105;

int farm[maxn][maxm];
int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int m,n,k,cnt;

void dfs(int x,int y)
{
	farm[x][y] = 1;//表示已经搜过这里 
	cnt++;
	for(int i = 0;i < 4;i++){
		int nx = x + dir[i][0];
		int ny = y + dir[i][1];
		if(1 <= nx && nx <= n && 1 <= ny && ny <= m && farm[nx][ny] == -1){
			dfs(nx,ny);
		}
	}
	
}

int main()
{
	int r,c;
	int ans;
	while(scanf("%d %d %d",&n,&m,&k) != EOF){
		memset(farm,0,sizeof(farm));
		ans = 0;
		for(int i = 0;i < k;i++){
			scanf("%d %d",&r,&c);
			farm[r][c] = -1;
		}
		for(int i = 1;i <= n;i++){
			for(int j = 1;j <= m;j++){
				cnt = 0;
				if(farm[i][j] == -1){//注意此处,一定要从有水且没有搜过的地方开始搜,否则容易WA 
					dfs(i,j);
					ans = max(ans,cnt);
				}	
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值