练习搜索之三维迷宫(HDU-2102)

A计划

题目:
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
输入:
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小N
M(1 <= N,M <=10)。T如上所意。接下去的前NM表示迷宫的第一层的布置情况,后NM表示迷宫第二层的布置情况。
输出:
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。

1
5 5 14
S*#*.
.#...
.....
****.
...#.

..*.P
#.*..
***..
...*.
*.#..

输出:

YES

分析:
一个简单的三维搜索,只不过有个坑点,“#”传送之后不能是“#”或者“*”,再或者不能直接是“P”。知道这些之后,直接BFS走起。

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
char date[2][15][15];
int vis[2][15][15];
int dir[][2] = { {1,0},{-1,0},{0,1},{0,-1} };
int n, m, time;
struct nood {

	int k, x, y;
	int step;
};
bool bfs(int k, int x, int y, int t) {
	queue<nood>q;
	nood s, e;
	s.k = k; s.x = x; s.y = y; s.step = t;
	q.push(s);
	while (!q.empty()) {
		s = q.front();
		//cout << s.k << " " << s.x << " " << s.y << " " << s.step << endl;
		q.pop();
		if (date[s.k][s.x][s.y] == 'P'&&s.step <= time)
			return true;
		for (int i = 0; i < 4; i++) {
			e.k = s.k;
			e.x = s.x + dir[i][0];
			e.y = s.y + dir[i][1];
			if (e.x >= 0 && e.x < n && e.y >= 0 && e.y < m && date[e.k][e.x][e.y] != '*') {
				if (date[e.k][e.x][e.y] != '#') {
					if (!vis[e.k][e.x][e.y]) {
						vis[e.k][e.x][e.y] = 1;
						e.step = s.step + 1;
						q.push(e);
					}
				}
				if (date[e.k][e.x][e.y] == '#') {
					if (date[!e.k][e.x][e.y] != '#'&&date[!e.k][e.x][e.y] != '*' && !vis[e.k][e.x][e.y] && !vis[!e.k][e.x][e.y]) {
						vis[e.k][e.x][e.y] = vis[!e.k][e.x][e.y] = 1;
						e.step = s.step + 1;
						e.k = !e.k;
						q.push(e);
					}
				}
			}
		}
	}
	return false;
}
int main()
{
	int c;
	cin >> c;
	while (c--) {
		memset(vis, 0, sizeof(vis));
		memset(date, '\0', sizeof(date));
		cin >> n >> m >> time;
		for (int i = 0; i < 2; i++)
			for (int j = 0; j < n; j++)
				cin >> date[i][j];
		vis[0][0][0] = 1;
		//bfs(0, 0, 0, 0);
		if (bfs(0,0,0,0))
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}
发布了40 篇原创文章 · 获赞 6 · 访问量 1414

猜你喜欢

转载自blog.csdn.net/qq_43321732/article/details/103941849
今日推荐