POJ - 1979 Red and Black(DFS)

链接:

http://poj.org/problem?id=1979


题意:

从起点(”标注@的地方“)开始走迷宫,标注“#”的地方不能走,统计一共有多少块可以走


思路:

这题可以转换为,求以起点开始的连通块,所含的位置个数

则只需要:从起点开始,对在迷宫范围内、没有走过,且可以走(不是"#")的迷宫位置,调用DFS进行递归(参数cnt,应设置为传引用,否则cnt应设置为全局变量,这样才能使得每次DFS时,对cnt的更新,可以保存下来


代码:

#include <iostream>
#include <cstring>
#include <string>
#define Clear(x, y) memset(x, y, sizeof(x))
using namespace std;
const int N = 25;
int m, n, startx, starty;
string maze[N];
int vis[N][N];
int d[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
void dfs(int x, int y, int&cnt)
{
	if (vis[x][y]) return;
	cnt++;
	vis[x][y] = 1;
	for (int i = 0; i < 4; i++)
	{
		int nowx = x + d[i][0];
		int nowy = y + d[i][1];
		if (!vis[nowx][nowy] && nowx >= 0 && nowx < m && nowy >= 0 && nowy < n && maze[nowx][nowy] == '.')
		{
			dfs(nowx, nowy, cnt);
		}
	}
	
}
int main()
{
	while (cin >> n >> m && m && n)
	{
		Clear(vis, 0);
		getchar();
		for (int i = 0; i < m; i++)
		getline(cin, maze[i]);
		
//		for (int i = 0; i < m; i++)
//		cout << maze[i] << endl;
//		
		bool found = false;
		
		for (int i = 0; i < m; i++)
		{
			if (found)break;  
			for (int j = 0; j < n; j++)
			if (maze[i][j] == '@')
			{
				found = true;
				startx = i;
				starty = j;
			}
		}
		
		int cnt = 0;
		dfs(startx, starty, cnt);
		cout << cnt << endl;
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值