题目:
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.
输入:
<p>* Line 1: Three space-separated integers: <i>N</i>, <i>M</i>, and <i>K</i><br>* Lines 2..<i>K</i>+1: Line <i>i</i>+1 describes one submerged location with two space separated integers that are its row and column: <i>R</i> and <i>C</i></p>
输出:
<p>* Line 1: The number of cells that the largest lake contains. </p>
样例:
3 4 5
3 2
2 2
3 1
2 3
1 1
4
题目大意:Farm Jhon的农场被水淹了,他的农场是N*M个格子,现在其中有的格子里面有水,有的没有,如果两个有水的格子共用的一条边,则他们就是连通的,让求最大的有水连通面积。
思路:dfs
1.因为只有一个角公用的是不算连通的,所以有4个方向。
2.farm数组:没水用0表示,有水用-1表示,已经搜过的地方用1表示。
求最大的就行了
代码:
#include<iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxx 105
using namespace std;
int farm[maxx][maxx];
int dir[4][2]={{1,0},{-1,0},{0,1},{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 next_x=x+dir[i][0];
int next_y=y+dir[i][1];
if(1<=next_x&&next_x<=n&&1<=next_y&&next_y<=m&&farm[next_x][next_y]==-1) //不越界保证有水
dfs(next_x,next_y);
}
}
int main()
{
int x,y;
int ans;
cin>>n>>m>>k;
memset(farm,0,sizeof(farm));
ans=0;
for(int i=0;i<k;i++)
{
cin>>x>>y;
farm[x][y]=-1;///表示有水
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cnt=0;
if(farm[i][j]==-1)
{
dfs(i,j);
ans=max(ans,cnt);
}
}
}
cout<<ans<<endl;
return 0;
}
本文介绍了一种使用深度优先搜索(DFS)算法解决农场洪水模拟问题的方法,旨在找出因洪水形成的最大湖泊覆盖的格子数量。通过构建网格地图并标记被水淹没的区域,该算法能够有效地确定最大的连续水域。
827

被折叠的 条评论
为什么被折叠?



