Dungeon Master
直接上中文了
Descriptions:
你被困在一個3D地牢中且繼續尋找最短路徑逃生!地牢由立方體單位構成,立方體單位中有的會充滿岩石。向上下前后左右移動一個單位需要一分鍾。你不能向對角線的四個方向移動且迷宮四周環繞着許多岩石。
是否可以逃出地牢?如果可以,則需要多少時間?
Input
輸入的第一行包含一個數,表示地牢的數量。
每個地牢的描述,其第一行包含三個數L,R和C(均小於等於30)。
L表示地牢的層數;R和C分別表示每層地牢的行與列的大小。
隨后輸入地牢的層數L,每層中包含R行,每行中包含C個字符。
每個字符表示地牢的一個單元。'#'表示岩石單元,'.'表示空白單元。你的起始位置在點'S',出口為'E'。
每層地牢的輸入后都有一個空行。當L,R和C均為0時,輸入結束。
Output
每個迷宮對應一行輸出。
如果可以逃生,則輸出如下
Escaped in x minute(s).
x為最短脫離時間。
如果無法逃生,則輸出如下
Trapped!
Sample Input
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
Sample Output
Escaped in 11 minute(s).
Trapped!
題目鏈接:
https://vjudge.net/problem/POJ-2251
最短路bfs,和二維的基本一樣,就是原來4個方向,現在6個方向,原來數組是二維,現在是三維,也相當於模板題了
AC代碼
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> #define mod 1000000007 #define ll long long #define INF 0x3f3f3f3f using namespace std; int sl,sx,sy; int el,ex,ey; char mp[35][35][35];//記錄地圖 int vis[35][35][35];//標記是否走過 int base[6][3] = { {-1,0,0},{1,0,0},{0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };//六個方向 int l,r,c; struct node { int f,x,y;//位置 int step;//步數 friend bool operator<(node a,node b)//步數小的現出來,即時間少 { return a.step>b.step;//優先隊列,步數小的先訪問 } }; priority_queue<node>q; /*************************bfs***************************/ void bfs() { node p; p.f=sl;//初始化 p.x=sx; p.y=sy; p.step=0; vis[sl][sx][sy]=1; q.push(p); while(!q.empty()) { node s=q.top(); q.pop(); if(s.f==el&&s.x==ex&&s.y==ey)//滿足條件 { printf("Escaped in %d minute(s).\n",s.step); return; } for(int i=0; i<6; i++)//6種走法 { int tl=s.f+base[i][0]; int tx=s.x+base[i][1]; int ty=s.y+base[i][2]; if(mp[tl][tx][ty]!='#'&&tl>=0&&tl<l&&tx>=0&&tx<r&&ty>=0&&ty<c&&!vis[tl][tx][ty])//判斷是否能走 { node e; e.f=tl; e.x=tx; e.y=ty; e.step=s.step+1; vis[e.f][e.x][e.y]=1; q.push(e); } } } cout<<"Trapped!"<<endl; } /**********************************主函數*********************************/ int main() { while(cin >> l >> r >>c,l+r+c) { for(int i=0; i<l; i++) { for(int j=0; j<r; j++) { cin >> mp[i][j]; for(int k=0; k<c; k++) { if(mp[i][j][k]=='S') { sl=i; sx=j; sy=k; } if(mp[i][j][k]=='E') { el=i; ex=j; ey=k; } } } } memset(vis,0,sizeof(vis));//每次都要初始化 bfs(); } }