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.
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题目大意:FJ的农场被淹了,他的农场可以被分成N * M个格子,其中有的格子有水,有的格子没水。如果两个有水的格子共用一条边的话,则说明它们是连通的,共用一个角不算连通。求连通区域的最大面积。
解题思路:DFS求连通块。每进行一次DFS,计数器加一。每次从没有被走过的点开始搜,可以将农场中有水的地方标记为-1,没有水的地方标记为0,已经搜过的地方标记为1,可以节省一个辅助数组的空间。
代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 105;
const int maxm = 105;
int farm[maxn][maxm];
int dir[4][2] = {{1,0},{0,1},{-1,0},{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 nx = x + dir[i][0];
int ny = y + dir[i][1];
if(1 <= nx && nx <= n && 1 <= ny && ny <= m && farm[nx][ny] == -1){
dfs(nx,ny);
}
}
}
int main()
{
int r,c;
int ans;
while(scanf("%d %d %d",&n,&m,&k) != EOF){
memset(farm,0,sizeof(farm));
ans = 0;
for(int i = 0;i < k;i++){
scanf("%d %d",&r,&c);
farm[r][c] = -1;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
cnt = 0;
if(farm[i][j] == -1){//注意此处,一定要从有水且没有搜过的地方开始搜,否则容易WA
dfs(i,j);
ans = max(ans,cnt);
}
}
}
printf("%d\n",ans);
}
return 0;
}