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. Input * Line 1: Three space-separated integers: N, M, and K 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 Source |
题意:给出一个图,n×m,有k个点有湖,k个带点的坐标已知,问最大的湖由多少个点构成。
解题思路:先用模拟,把题目中给出的图转换成符号图。这里我用的是.代表陆地,#代表湖。然后再无脑深搜,值得注意的是里是四连块,也就是说搜索的时候只需要搜索四个方向即可。然后我给dfs函数增加了一个参数num,这个参数算是标记和湖的编号。然后经过无脑深搜后,flag数组就已经标记好,剩下的就非常简单了,因为各个湖已经用不同的num标记好所以我们只需要找到num个湖中最大的那个就行了。以下是我的代码(讲的可能啰嗦了一些)
#include <stdio.h>
#include <memory.h>
#define maxn 105
int n,m,flag[maxn][maxn];
int mm[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
char pic[maxn][maxn];
int max(int x,int y)
{
return x>y?x:y;
}
void dfs(int r,int s,int num)
{
if(r>=n||r<0||s>=m||s<0) return;
if(flag[r][s]>0||pic[r][s]!='#') return;
flag[r][s]=num;
for(int i=0;i<4;i++)
dfs(r+mm[i][0],s+mm[i][1],num);
}
int main()
{
int k;
scanf("%d%d%d",&n,&m,&k);
memset(pic,'.',sizeof(pic));
memset(flag,0,sizeof(flag));
for(int i=0; i<k; i++)
{
int x,y;
scanf("%d%d",&x,&y);
pic[x-1][y-1]='#';
}
int num=0;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(flag[i][j]==0&&pic[i][j]=='#') dfs(i,j,++num);
int sum=0,t;
for(int i=1;i<=num;i++)
{
t=0;
for(int j=0;j<n;j++)
for(int k=0;k<m;k++)
if(flag[j][k]==i) t++;
sum=max(sum,t);
}
printf("%d\n",sum);
return 0;
}