KuangBin 专题一:简单搜索 Dungeon Master

题目链接:
传送门

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

const int N = 31;
struct node { int x, y, z; };
//操作数组
node op[6] = { {0,0,1},{0,0,-1} ,{1,0,0}, {-1,0,0} ,{0,1,0} ,{0,-1,0} };
//定义三维坐标和起始点
int len[N][N][N], l, r, c, sx, sy, sz, ex, ey, ez;
//用于标记已搜过的结点
int used[N][N][N];
//一个判断该点是否在合法区域内的函数
bool inMap(int x, int y, int z)
{
	return x >= 1 && x <= c && y >= 1 && y <= r && z >= 1 && z <= l;
}
//bfs函数体
void bfs(int x, int y, int z)
{
    //创建队列如果没有
    queue<node> q;
    node start= {x,y,z};
    q.push(start);
    //把起点标记为已查
	used[x][y][z] = 1;
	len[x][y][z] = 0;
    //在队列不为空的情况下
	while (!q.empty())
	{
        //获取当前顶部的元素
		node cur = q.front();
        //向几个方向进行搜索
		for (int i = 0; i < 6; i++)
		{
            //对点的各个坐标进行处理
			int curX = cur.x + op[i].x;
			int curY = cur.y + op[i].y;
			int curZ = cur.z + op[i].z;
            //判断是否符合条件(是否已被搜索,是否超出地图)
			if (inMap(curX, curY, curZ) && !used[curX][curY][curZ])
			{
				used[curX][curY][curZ] = 1;
				len[curX][curY][curZ] = len[cur.x][cur.y][cur.z] + 1;
                //把新的点压入栈中
				node news= {curX,curY,curZ};
				q.push(news);
			}
		}
		q.pop();
	}
}
int main()
{
	while (cin >> l >> r >> c)
	{
		if (l == 0 && r == 0 && c == 0) break;
		memset(len, 0, sizeof(len));
		memset(used, 0, sizeof(used));
		for (int i = 1; i <= l; i++)
			for (int j = 1; j <= r; j++)
				for (int k = 1; k <= c; k++)
				{
					char a;
					cin >> a;
					if (a == 'S')
					{
						sx = k;
						sy = j;
						sz = i;
					}
					else if (a == 'E')
					{
						ex = k;
						ey = j;
						ez = i;
					}
					else if (a == '#') used[k][j][i] = 1;
					else used[k][j][i] = 0;
				}
		bfs(sx, sy, sz);
		if (len[ex][ey][ez] == 0)
			cout << "Trapped!" << endl;
		else
			cout << "Escaped in " << len[ex][ey][ez] << " minute(s)." << endl;
	}
	return 0;
}

这道题是一个三维的搜索,这道题因为是找最短的路所以感觉bfs会比较好做。向上下左右前后进行搜索,最后查看结束点的最短路径长度,如果是0则说明这是一个不连通的点。也就是Trapped的情况,否则输出最短的路长。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值