Topic Links:
http://acm.hdu.edu.cn/showproblem.php?pid=1253
Main topic:
There is a three-dimensional cube maze, starting at the position (0,0,0), leaving the position for (a-1,b-1,c-1), the maze of 0 represents
Road, 1 means the wall, you can only walk from one coordinate to one of the adjacent six coordinates. Q: The shortest time to leave this maze
is how much.
Ideas:
It is easy to think of BFS to find the shortest path. is only three-dimensional, with a two-dimensional array to store six directions. Use the queue to
Implementation of BFS.
AC Code:
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include < queue>using namespace Std;const int Dire[6][3] = {{0,0,-1},{0,0,1},{0,-1,0},{0,1,0},{-1,0,0},{1,0,0}};int Map[55][ 55][55];struct node{int x; int y; int z; int time;}; int BFS (int a,int b,int c,int time) {Node p,p1; int ans = 0xffffff0; p.x = 0; P.Y = 0; p.z = 0; P.time = 0; Queue<node> Q; Q.push (P); while (!q.empty ()) {p = Q.front (); Q.pop (); if (P.time > Time) continue; if (p.x = = A-1 && p.y = = B-1 && p.z = C-1) ans = min (ans,p.time); for (int i = 0; i < 6; ++i) {p1.x = p.x + dire[i][0]; P1.Y = p.y + dire[i][1]; P1.z = P.z + dire[i][2]; if (p1.x < 0 | | P1.y < 0 | | P1.z < 0 | | p1.x >= A | | p1.y >= B | | p1.z >= C) continue; if (Map[p1.x][p1.y][p1.z]) Continue MAP[P1.X][P1.Y][P1.Z] = 1; P1.time = p.time + 1; Q.push (p1); }} return ans; int main () {int T; scanf ("%d", &t); while (t--) {int a,b,c,time; scanf ("%d%d%d%d", &a,&b,&c,&time); for (int i = 0, i < A; ++i) for (int j = 0; j < B; ++j) for (int k = 0; k < C; ++k) Map[i][j][k] = 1; for (int i = 0, i < A; ++i) for (int j = 0; j < B; ++j) for (int k = 0; k < C; ++k) scanf ("%d", &map[i][j][k]); int ans = BFS (a,b,c,time); if (ans > Time) printf (" -1\n"); else printf ("%d\n", ans); } return 0;}
HDU1253 Victory Grand Escape "BFS"