Avoid The Lakes acm入门 day1---bfs_dfs第四题

农场遭遇洪水,需计算由k个淹水区域组成的最大相连水域面积。利用深度优先搜索或广度优先搜索找出最大湖泊。

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: N, M, 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.

解释:n行m列的农场中,有k个被淹没的田地坐标,要计算被淹没的最大面积,上下左右为相邻,算出相邻点最多的一块
这道题其实和第一道是同样的,只是相邻条件不一样,所以思路依旧是dfs,bfs均可以
因此依旧是dfs,bfs均可以,遍历整个数组。

Sample Input

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

Sample Output

4
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int n, m, k;
int mat[101][101];
int vis[101][101];
void dfs(int x, int y, int& tot)
{
	if (mat[x][y] == 0) return;
	tot++;
	vis[x][y] = 1;
	if (x + 1 < n && vis[x + 1][y] == 0) dfs(x + 1, y, tot);
	if (x - 1 >= 0 && vis[x - 1][y] == 0) dfs(x - 1, y, tot);
	if (y + 1 < m && vis[x][y + 1] == 0) dfs(x, y + 1, tot);
	if (y - 1 >= 0 && vis[x][y - 1] == 0) dfs(x, y - 1, tot);
}

int main()
{

	while (scanf("%d %d %d", &n, &m, &k) != EOF)
	{
		memset(mat, 0, sizeof(mat));
		memset(vis, 0, sizeof(vis));
		for (int i1 = 0; i1 < k; i1++)
		{
			int x, y;
			cin >> x >> y;
			mat[x - 1][y - 1] = 1;
		}
		int totm = 0;
		for (int i = 0; i < n; i++)
			for (int i1 = 0; i1 < m; i1++)
			{
				int tot = 0;
				if (vis[i][i1] == 0) dfs(i, i1, tot);
				if (tot > totm) totm = tot;
			}
		printf("%d\n", totm);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值