3D逃亡-简单搜素练习2

POJ2251(BFS-3D)


解题报告:

1.题意简单,就是个3D的搜索,从S到E输出距离。依照题意不妨bfs搜索。那好,搜索退出条件是当前状态非法,或者到达E。

2.状态? 直接map[l][r][c]就好了。为了方便输入,故使用map[l][r][c]而非[r][c][l]。依照题意,很容易看出不需要定义一个标记数组vis[][][],走过的直接map[][][] == '#'处理。

3.状态转移? 6个方向,forward,back,up,down, right,left。注意是6,不是经常写的4,for循环处理的时候不要出错。


More:代码编写是出现一个小问题,debug排错解决了。详见代码。


//http://acm.hust.edu.cn/vjudge/contest/view.action?cid=65959#problem/B
//

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 31;
char map[maxn][maxn][maxn];	//记录map
int dir[6][3] = {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};//fbdurl,方向
int L, R, C;
int sl, sr, sc;

struct Node
{
	int l, r, c, dis;
	Node(){}
	Node(int x, int y, int z, int d): l(x), r(y), c(z), dis(d){};
};

int bfs()
{
	queue<Node> q;
	q.push(Node (sl, sr, sc, 0));		//起始位置入队
	map[sl][sr][sc] = '#';				//起始位置标记已走过
	while (!q.empty())
	{
		Node u = q.front(); q.pop();
		for (int d = 0; d < 6; d++)
		{
			int nl = u.l + dir[d][0];
			int nr = u.r + dir[d][1];
			int nc = u.c + dir[d][2];
			if (nl < 0 || nc < 0 || nr < 0 || nl >= L || nc >= C || nr >= R) continue;
			if (map[nl][nr][nc] == '#') continue;
			q.push(Node(nl, nr, nc, u.dis + 1));
			if (map[nl][nr][nc] == 'E')
				return u.dis + 1;
			map[nl][nr][nc] = '#';			//起初这句写在了if (map[nl][nr][nc] == 'E')前面,出现问题。。。
											//debug设置条件断点nl == 2 && nr == 3 && nc == 4发现错误。。。
		}
	}
	return -1;
}

int main()
{
	while (scanf("%d%d%d%*c", &L, &R, &C) != EOF && (L || R || C))
	{
		bool flag = false;
		for (int l = 0; l < L; l++)
		{
			for (int r = 0; r < R; r++)
			{
				gets(map[l][r]);
				if (!flag) for (int c = 0; c < C; c++)		//起始位置
					if (map[l][r][c] == 'S')
						sl = l, sr = r, sc = c, flag = true;
			}
			scanf("%*c");
		}
		int ans;
		if((ans = bfs()) == -1) puts("Trapped!");
		else printf("Escaped in %d minute(s).\n", ans);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值