POJ 2386 Lake Counting

本文介绍了一个简单的DFS算法实现,旨在帮助初学者理解深度优先搜索的基本概念及其实现过程。通过实例演示了如何使用DFS解决特定问题,并提供了输入输出样例,以便读者实践操作。

 基本的DFS,用于练手

#include <stdio.h>

char arr[110][110];
int max_row;
int max_col;

void dfs(int cur_row, int cur_col){
	if(cur_row<1 || cur_row>max_row)
		return;

	if(cur_col<1 || cur_col>max_col)
		return;

	if('.' == arr[cur_row][cur_col])
		return;

	arr[cur_row][cur_col] = '.';
	dfs(cur_row, cur_col-1);
	dfs(cur_row-1, cur_col-1);
	dfs(cur_row-1, cur_col);
	dfs(cur_row-1, cur_col+1);
	dfs(cur_row, cur_col+1);
	dfs(cur_row+1, cur_col+1);
	dfs(cur_row+1, cur_col);
	dfs(cur_row+1, cur_col-1);
}

void solve(int row, int col){
	int i, j, cnt;

	max_row = row;
	max_col = col;

	cnt = 0;
	for(i=1; i<=row; i++){
		for(j=1; j<=col; j++){
			if('W' == arr[i][j]){
				cnt++;
				dfs(i, j);
			}
		}
	}
	printf("%d\n", cnt);
}


int main(void){
	int row, col, i;

	//freopen("input.dat", "r", stdin);
	while(EOF != scanf("%d %d", &row, &col)){
		for(i=1; i<=row; i++)
			scanf("%s", arr[i]+1);
		solve(row, col);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值