POJ 2386 Lake Counting 搜索题解

简单的深度搜索就可以了,看见有人说什么使用并查集,那简直是大算法小用了。

因为可以深搜而不用回溯,故此效率就是O(N*M)了。

技巧就是增加一个标志P,每次搜索到池塘,即有W字母,那么就认为搜索到一个池塘了,P值为真。

搜索过的池塘不要重复搜索,故此,每次走过的池塘都改成其他字母,如'@',或者'#',随便一个都可以。

然后8个方向搜索。

#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <limits.h>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
const int MAX_N = 101;
char pond[MAX_N][MAX_N];
const char VIS = '@';
int N, M;
bool P;

inline bool isLegal(int r, int c)
{
	return 0<=r && 0<=c && r<N && c<M && pond[r][c] == 'W';
}

void getPond(int r, int c)
{
	if (!isLegal(r, c)) return ;
	P = true;
	pond[r][c] = VIS;
	getPond(r+1, c);
	getPond(r-1, c);
	getPond(r, c+1);
	getPond(r, c-1);
	getPond(r+1, c+1);
	getPond(r+1, c-1);
	getPond(r-1, c+1);
	getPond(r-1, c-1);//eight direction search
}

int main()
{
	while (~scanf("%d %d", &N, &M))
	{
		getchar();
		for (int i = 0; i < N; i++)
		{
			gets(pond[i]);
		}
		int ans = 0;
		for (int i = 0; i < N; i++)
		{
			for (int j = 0; j < M; j++)
			{
				P = false;
				getPond(i, j);
				ans += P;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值