Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
Input
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小N*M(1 <= N,M <=10)。T如上所意。接下去的前N*M表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。
Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。
Sample Input
1
5 5 14
S*#*.
.#…
…..
****.
…#.
..*.P
#.*..
***..
…*.
*.#..
Sample Output
YES
Source
HDU 2007-6 Programming Contest
思路:双层BFS。有几个要注意的地方。预处理时,将上下层分别为#,*和上下层均为#的点标记为*。另外,虽然传送不需要时间,但从其他点走到#是需要时间的。
AC代码:
#include <cstdio> #include <queue> using namespace std; int n, m, t; char map[3][15][15]; const int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; struct node { int x, y, z, step; bool operator == (const node b) const { return x == b.x && y == b.y && z == b.z; } }; node start, goal; queue <node> q; void input() { scanf("%d%d%d", &n, &m, &t); for (int i = 0; i < n; i++) scanf("%s", map[0][i]); for (int i = 0; i < n; i++) scanf("%s", map[1][i]); } bool check(int z, int x, int y) { if (x < 0 || x >= n || y < 0 || y >= m || map[z][x][y] == '*') return 0; return 1; } void pre() { while (!q.empty()) q.pop(); for (int i = 0; i < 2; i++) for (int j = 0; j < n; j++) for (int k = 0; k < m; k++) { if (map[i][j][k] == 'P') goal = (node){j, k, i, 0}; if (map[i][j][k] == '#') { if (map[!i][j][k] == '*') map[i][j][k] = '*'; else if (map[!i][j][k] == '#') map[i][j][k] = map[!i][j][k] = '*'; } } start = (node){0, 0, 0, 0}; map[0][0][0] = '*'; } void bfs() { pre(); q.push(start); while (!q.empty()) { node u = q.front(); q.pop(); if (u == goal && u.step <= t) { printf("YES\n"); return; } if (u.step > t) break; node next; for (int i = 0; i < 4; i++) { next.x = u.x + dx[i]; next.y = u.y + dy[i]; if (!check(u.z, next.x, next.y)) continue; if (map[u.z][next.x][next.y] == '#') next.z = !u.z; else next.z = u.z; next.step = u.step + 1; map[next.z][next.x][next.y] = '*'; q.push(next); } } printf("NO\n"); } int main() { int T; scanf("%d", &T); while (T--) { input(); bfs(); } return 0; }
0 条评论