题目描述
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.
与UVA572不同的是,本题不需求连通块的数量,需要的是最大的连通分量的大小,而且连通的规则也改为了只能上下左右才可以。
日常安利本题我的博客
思路分析
这个题的思路是这样的,除了之前说过的求连通分量的数组外,额外加了一个存连通分量大小的数组,最后将这个数组有大到小排序,输出数组的第一个元素即可。
这个题代码部分DFS函数没写好,因为其他的错误以为DFS边界写错了,于是添加了冗余代码。
DFS判断边界情况只需要考虑当前情况即可。引以为戒。
代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string>
#include<set>
#include<time.h>
using namespace std;
#define mem(a) memset(a,0,sizeof(a))
#define ll long long
const double eps = 1e-8;
const int maxn = 110;//须填写
const int inf = 0x3f3f3f3f;
int n,m;
int pic[maxn][maxn];
int vis[maxn][maxn];
int num[maxn*maxn];
bool cmp(int a,int b)
{
return a>b;
}
void dfs(int x,int y,int s)
{
if(x<1||y<1||x>n||y>m)
return ;
if(!vis[x-1][y]&&pic[x-1][y]==1&&x-1>=1)
{
vis[x-1][y]=s;
num[s]++;
dfs(x-1,y,s);
}
if(!vis[x+1][y]&&pic[x+1][y]==1&&x+1<=n)
{
vis[x+1][y]=s;
num[s]++;
dfs(x+1,y,s);
}
if(!vis[x][y-1]&&pic[x][y-1]==1&&y-1>=1)
{
vis[x][y-1]=s;
num[s]++;
dfs(x,y-1,s);
}
if(!vis[x][y+1]&&pic[x][y+1]==1&&y+1<=m)
{
vis[x][y+1]=s;
num[s]++;
dfs(x,y+1,s);
}
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("sample.out", "w", stdout);
mem(vis);
mem(pic);
mem(num);
int k,x,y;
int results = 0;
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<k;i++)
{
scanf("%d%d",&x,&y);
pic[x][y] = 1;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(vis[i][j]==0&&pic[i][j]==1)
{
vis[i][j] = ++results;
num[results]++;
dfs(i,j,results);
//printf("%d %d %d\n",i,j,num[results]);
}
}
}
sort(num,num+results+1,cmp);
printf("%d\n",num[0]);
return 0;
}