POJ 3620 Avoid The Lakes(dfs)

Avoid The Lakes
 

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 6964

 

Accepted: 3697

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 ≤ KN × 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

 

题意:有一片牧场,牧场里有池塘,现在用一N*M矩形网格表示牧场,若网格是有水区域,该网格的上下左右四个方向的网格也有水,则可以他们是同一片池塘。题中给出有水网格的坐标,求最大池塘的网格数是多少

 

题解:建立一个二维数组,将有水的网格标记为1,深搜即可。

 

代码如下:

 

#include<cstdio>
#include<cstring>
int n,m,sum,count,map[105][105];
int dir[4][2]={{1,0},{-1,0},{0,-1},{0,1}};

void dfs(int x,int y)
{
	int i,dx,dy;
	map[x][y]=0;
	count++;
	for(i=0;i<4;i++)
	{
		dx=x+dir[i][0];  dy=y+dir[i][1];
		if(dx>0&&dx<=n&&dy>0&&dy<=m&&map[dx][dy])//判断网格是否是合法的有水网格 
			dfs(dx,dy);
	}
	if(count>sum)
	   sum=count;
}

int main()
{
	int k,i,j,r,c;
	while(scanf("%d%d%d",&n,&m,&k)!=EOF)
	{
		memset(map,0,sizeof(map));
		while(k--)
		{
			scanf("%d%d",&r,&c);
			map[r][c]=1;//标记有水的网格 
		}
		sum=0;
		for(i=1;i<=n;i++)
		{
			for(j=1;j<=m;j++)
			{
				if(map[i][j])
				{
					count=0;
					dfs(i,j);
				}
			}
		}
		printf("%d\n",sum);
	}
	return 0;
}


 

 

你可能感兴趣的:(POJ 3620 Avoid The Lakes(dfs))