题目链接:http://poj.org/problem?id=2251
参考了一下大神们的解法。也有用深搜的。然而,之前不久看到一句话,最短路径——BFS。
参考:http://blog.csdn.net/lyy289065406/article/details/6647938
#include <stdio.h> #include <algorithm> #include <string.h> #include <queue> using namespace std; char map[35][35][35];///存放地图 bool hash[35][35][35];///这条路是否走过 struct point{ int x; ///l int y; ///r int z; ///c int step;///移动的步数 }; int main() { int l,r,c; while(scanf("%d%d%d",&l,&r,&c),l&&r&&c) { int i,j,k; point start; memset(hash,false,sizeof(hash)); for(i=0;i<l;i++) { for(j=0;j<r;j++) { scanf("%s",map[i][j]); for(k=0;k<c;k++) { if(map[i][j][k]=='S') { ///对起点初始化 start.x=i; start.y=j; start.z=k; start.step=0; hash[i][j][k]=true;///这条路走过了 } } } } queue<point> bfs; bfs.push(start);///入队 bool found=false; ///是否找到最优解 while(!bfs.empty()) { point tmp=bfs.front(); bfs.pop(); if(map[tmp.x][tmp.y][tmp.z]=='E') { found=true; printf("Escaped in %d minute(s). ",tmp.step); break; } tmp.step++; point tmp2; if(tmp.x>0) ///向下走 { tmp2=tmp; tmp2.x--; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { ///如果下一层不是障碍物并且没走过,则往下走,标记该点,入队 hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } ///向上走 if(tmp.x<l-1) { tmp2=tmp; tmp2.x++; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } ///向北走 if(tmp.y>0) { tmp2=tmp; tmp2.y--; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } ///向南走 if(tmp.y<r-1) { tmp2=tmp; tmp2.y++; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } ///向西走 if(tmp.z>0) { tmp2=tmp; tmp2.z--; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } ///向东走 if(tmp.z<c-1) { tmp2=tmp; tmp2.z++; if(map[tmp2.x][tmp2.y][tmp2.z]!='#'&&hash[tmp2.x][tmp2.y][tmp2.z]==false) { hash[tmp2.x][tmp2.y][tmp2.z]=true; bfs.push(tmp2); } } } if(!found) printf("Trapped! "); } return 0; }