1. 程式人生 > >POJ-2251 三維迷宮

POJ-2251 三維迷宮

ring 一個 mem getch 清空 左右 三維 程序 %d

題目大意:給一個三維圖,可以前後左右上下6種走法,走一步1分鐘,求最少時間(其實就是最短路)

分析:這裏與二維迷宮是一樣的,只是多了2個方向可走,BFS就行(註意到DFS的話復雜度為O(6^n)肯定會TLE)

  1 #include <iostream>
  2 #include <cstdio>
  3 #include <cstring>
  4 #include <iterator>
  5 #include <queue>
  6 using namespace std;
  7 #define N 33
  8 #define
M 30000 9 struct p 10 { 11 int ll,rr,cc,ans; 12 }; 13 typedef struct p sp; 14 char m[N][N][N]; 15 int mark[N][N][N]; 16 int l,r,c; 17 int dir[3][6]={{1,-1,0,0,0,0},{0,0,-1,1,0,0},{0,0,0,0,-1,1}}; 18 19 void test()//可跟蹤mark數組debug程序 20 { 21 int i,j,k; 22 for (i=0;i<l;i++) 23 { 24 for
(j=0;j<r;j++) 25 { 26 for (k=0;k<c;k++) 27 { 28 printf("%d",mark[i][j][k]); 29 } 30 printf("\n"); 31 } 32 printf("\n"); 33 } 34 } 35 36 int lawful(int x,int y,int z) 37 { 38 if (x<0||x>=l||y<0
||y>=r||z<0||z>=c||m[x][y][z]==#)//判斷合法性要完整!!!m[x][y][z]==‘#‘ 39 { 40 return 0; 41 } 42 else 43 { 44 return 1; 45 } 46 } 47 48 void solve() 49 { 50 sp point,point1; 51 int i,j,k; 52 queue<p> q;//要定義在函數內,使其每次測試都能清空隊列!!! 53 memset(mark,0,sizeof(mark)); 54 for (i=0;i<l;i++) 55 { 56 for (j=0;j<r;j++) 57 { 58 for (k=0;k<c;k++) 59 { 60 if (m[i][j][k]==S) 61 { 62 point.ll=i; 63 point.rr=j; 64 point.cc=k; 65 point.ans=0; 66 mark[i][j][k]=1;//要記得給第一步步打上標記!!! 67 q.push(point); 68 } 69 } 70 } 71 } 72 while (!q.empty()) 73 { 74 point=q.front(); 75 q.pop(); 76 if (m[point.ll][point.rr][point.cc]==E) 77 { 78 printf("Escaped in %d minute(s).\n",point.ans); 79 return; 80 } 81 for (i=0;i<6;i++) 82 { 83 point1.ll=point.ll+dir[0][i]; 84 point1.rr=point.rr+dir[1][i]; 85 point1.cc=point.cc+dir[2][i]; 86 point1.ans=point.ans+1; 87 if (lawful(point1.ll,point1.rr,point1.cc)&&!mark[point1.ll][point1.rr][point1.cc])//要記得判斷標記!!! 88 { 89 q.push(point1); 90 mark[point1.ll][point1.rr][point1.cc]=1;//記得更新標記!!! 91 // test(); 92 } 93 } 94 } 95 printf("Trapped!\n"); 96 97 } 98 99 int main() 100 { 101 int i,j; 102 while (scanf("%d %d %d",&l,&r,&c)) 103 { 104 if (l==0&&r==0&&c==0) 105 { 106 break; 107 } 108 for (i=0;i<l;i++) 109 { 110 for (j=0;j<r;j++) 111 { 112 scanf("%s",m[i][j]);//輸入字符的快捷方法 113 getchar(); 114 } 115 } 116 solve(); 117 } 118 119 return 0; 120 }

POJ-2251 三維迷宮