UVA 532 - Dungeon Master

来源:互联网 发布:个人备忘录java程序 编辑:程序博客网 时间:2024/05/21 00:51

题目大意:从起点能否到达终点,如果能就输出起步数

解题思路:用 BFS 即可判断是否能到达终点切输出其最少步数

#include <cstdio>#include <queue>using namespace std;int level, row, column;int dir[6][3] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};char dungeon[35][35][35];struct Node {int x;int y;int z;int step;};struct Node start;int BFS() {queue<Node> Q;Q.push(start);while (!Q.empty()) {Node root;root = Q.front();Q.pop();for (int i = 0; i < 6; i++) {Node child;child.z = root.z + dir[i][0];child.x = root.x + dir[i][1];child.y = root.y + dir[i][2];if (child.z < 0 || child.z >= level || child.x < 0 || child.x >= row || child.y < 0 || child.y >= column || dungeon[child.z][child.x][child.y] == '#')continue; //越界、碰墙就停止child.step = root.step + 1;if (dungeon[child.z][child.x][child.y] == 'E') {   //到达终点就输出起点到终点所需的 stepprintf("Escaped in %d minute(s).\n", child.step);return 0;}Q.push(child);dungeon[child.z][child.x][child.y] = '#'; //假如没到终点就标记已走过}}return 1;}int main() {while (scanf("%d%d%d", &level, &row, &column), level) {for (int i = 0; i < level; i++)for (int j = 0; j < row; j++) {scanf("%s", dungeon[i][j]);for (int k = 0; k < column; k++)if (dungeon[i][j][k] == 'S') {start.z = i;start.x = j;start.y = k;start.step = 0;}}if (BFS())printf("Trapped!\n");}return 0;}


0 0