http://poj.org/problem?id=3620
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.
Sample Input
3 4 5
3 2
2 2
3 1
2 3
1 1
Sample Output
4
题目大意:农场被水淹没了,有几个地方(点)是充满水的,然后两个在同一水平线或同一垂直线上的点可以认为是连通在一起的,让你求几个连通块中最大的连通块的点的数目。题目输入的第二行到第k+1行就是充满水的点的坐标。
思路:首先,dfs求连通块,把同属于一个连通块的打上记号i,再用一个数组f[i]表示该连通块的点的数目,最大的连通块的点的数目自然就是MAX(f[0],f[1]……f[n])了,当然这个过程可以在dfs的时候完成。详情看代码注释吧。
#include<iostream>
#include<cstdio>
#include<stack>
#include<cmath>
#include<cstring>
#include<queue>
#include<set>
#include<algorithm>
#include<iterator>
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int s[105][105]; //存储地图
int bh[105][105]; //记录点(x,y)的标号
int f[10005]; //记录各连通块的点的数目
int MAX=0; //计算最大值
int n,m;
int d[4][2]={{-1,0},{0,-1},{1,0},{0,1}}; //四个方向
void dfs(int x,int y,int num);
int main()
{
int k;
scanf("%d%d%d",&n,&m,&k);
int t1,t2;
for(int i=0;i<k;i++)
{
scanf("%d%d",&t1,&t2);
s[t1-1][t2-1]=1; // 地图上 1 代表该点充满水 否则代表干旱的
}
int cnt=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(bh[i][j]==0&&s[i][j]==1)//满足题意的且不属于其他连通块的点
dfs(i,j,++cnt);
printf("%d\n",MAX);
return 0;
}
void dfs(int x,int y,int num)
{
if(x<0||x>=n||y<0||y>=m) //超出边界
return ;
if(bh[x][y]||s[x][y]==0) //已经被打上标号了或者不是满足题意的点
return ;
bh[x][y]=num; //打上标号
MAX=max(MAX,++f[num]); //维护最大值
for(int i=0;i<4;i++) //向四个方向扩散
dfs(x+d[i][0],y+d[i][1],num); //同属于一个连通块 num不用变
}