POJ 2251 Dungeon Master(地牢)

题目链接:POJ 2251

题意:迷宫问题。

分析:

二维变三维,BFS。注意存储下标含义即可。

a[j][k][i] = s[k];
if (s[k] == 'S')
{
        sx = j, sy = k, sz = i;
	//i相当于z轴,对应L;j相当于x轴,对应C;k相当于y轴,对应R
}
else if (s[k] == 'E')
{
	ex = j, ey = k, ez = i;
}

CODE:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int maxn = 31;
char s[maxn], a[maxn][maxn][maxn];
int vis[maxn][maxn][maxn];
int dir[6][3] = { {0,0,1},{0,1,0},{1,0,0},{-1,0,0},{0,-1,0},{0,0,-1} };
int sx, sy, sz, ex, ey, ez, L, R, C;

struct Node {
	int x, y, z;
	int step;
}cur,nextnode;

int valid(int x, int y, int z)
{
	if (x < 0 || y < 0 || z < 0 || x >= R || y >= C || z >= L) return 0;//下标越界
	if (vis[x][y][z] == 1) return 0;//访问过该点
	if (a[x][y][z] == '#') return 0;//遇到墙
	return 1;
}
int bfs()
{
	queue<Node> q;
	cur.x = sx, cur.y = sy, cur.z = sz;
	cur.step = 0;
	q.push(cur);
	vis[sx][sy][sz] = 1;
	while (!q.empty())
	{
		cur = q.front();
		q.pop();
		for (int i = 0;i < 6;i++)
		{
			nextnode.x = cur.x + dir[i][0];
			nextnode.y = cur.y + dir[i][1];
			nextnode.z = cur.z + dir[i][2];
			nextnode.step = cur.step + 1;
			if (!valid(nextnode.x, nextnode.y, nextnode.z)) continue;
			if (nextnode.x == ex&&nextnode.y == ey&&nextnode.z == ez) return nextnode.step;//找到出口
			vis[nextnode.x][nextnode.y][nextnode.z] = 1;
			//cout << nextnode.x << " " << nextnode.y << " " << nextnode.z << endl;
			q.push(nextnode);
		}
	}
	return -1;
}

int main()
{
#ifdef LOCAL
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	while (cin >> L >> R >> C)
	{
		if (L == 0 && R == 0 && C == 0) break;
		for (int i = 0;i < L;i++)
		{
			for (int j = 0;j < R;j++)
			{
				cin >> s;
				for (int k = 0;k < C;k++)
				{
					a[j][k][i] = s[k];
					if (s[k] == 'S')
					{
						sx = j, sy = k, sz = i;
						//cout << sx << " " << sy << " " << sz << endl;
					}
					else if (s[k] == 'E')
					{
						ex = j, ey = k, ez = i;
						//cout << ex << " " << ey << " " << ez << endl;
					}
				}
			}
		}
		/*
		for (int i = 0;i < L;i++)
		{
			for (int j = 0;j < R;j++)
				puts(a[i][j]);
			putchar('\n');
		}
		*/
		memset(vis, 0, sizeof(vis));
		int ans = bfs();
		if (ans == -1) cout<<"Trapped!" << endl;
		else printf("Escaped in %d minute(s).\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值