POJ 2386 Lake Counting(深搜)

Lake Counting

Time Limit: 1000MS     Memory Limit: 65536K

Total Submissions: 17917     Accepted: 9069

Description

Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water ('W') or dry land ('.'). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John's field, determine how many ponds he has.

Input

Line 1: Two space-separated integers: N and M
Lines 2..N+1: M characters per line representing one row of Farmer John's field. Each character is either 'W' or '.'. The characters do not have spaces between them.

Output

Line 1: The number of ponds in Farmer John's field.

Sample Input

10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

Sample Output

3

思路

从任意的W开始,不停地把邻接的部分用'.'代替。 1次DFS后与初始的这个W连接的所有W就都被替
换成了'.',因此直到图中不再存在W为止,总共进行DFS的次数就是答案了。 8个方向共对应了8种
状态转移,每个格子作为DFS的参数至多被调用一次,所以复杂度为O(8×N×M)=O(N×M)。

#include<stdio.h>
#define MAX_N 105
#define MAX_M 105
char field[MAX_N][MAX_M];
int N,M;


void dfs(int x,int y)
{
	
	int dx,dy,nx,ny;
	
	field[x][y] = '.'; //将现在位置替换为'.'; 
	
	for (dx = -1;dx < 2;dx++)  //遍历移动的8个方向 
	{
		for (dy = -1;dy < 2;dy++)
		{
			nx = x + dx,ny = y + dy;
			if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W')
			{                                   //判断(nx,ny)是不是在园子内 
				dfs(nx,ny);
			}
		}
	}
}


int main()
{
	int i,j,res = 0;
	char tmp;
	scanf("%d%d",&N,&M);
	getchar();
	for (i=0;i<N;i++)
	{
		for (j=0;j<M;j++)
		{
			scanf("%c",&field[i][j]);
			if (j==M-1)
			{
				scanf("%c",&tmp);
			}
		}
	}
	
	for (i = 0;i < N;i++)
	{
		for (j = 0;j < M;j++)
		{
			if (field[i][j] == 'W')
			{
				dfs(i,j);
			    res++;
			}
		}
	}
	
	printf("%d\n",res);
	return 0;
}
posted @   zxzhang  阅读(347)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示

目录导航