题目链接:https://cn.vjudge.net/problem/POJ-2251
题意:有l层平面,每个平面的大小是r*c,问从S到E最小的花费
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <algorithm> #define mem(a,b) memset(a,b,sizeof(a)); using namespace std; #define INF 0x3f3f3f3f typedef long long ll; int dir[4][2] = {0,1,0,-1,1,0,-1,0}; const int maxn = 50005; int l,r,c,vis[40][40][40],ans; char s[40][40][40]; bool flag; struct node { int x,y,z,val;//val为起点到该点的花费 node(int xx,int yy,int zz,int vall):x(xx),y(yy),z(zz),val(vall){}; }; void bfs(int ii,int jj,int kk) {//(z,x,y) queue<node>q; q.push(node(jj,kk,ii,0));//(x,y,z) vis[ii][jj][kk] = 1; while(!q.empty()) { node temp = q.front(); q.pop(); int fx = temp.x,fy=temp.y,fz =temp.z,fv = temp.val; if(s[fz][fx][fy] == 'E') { flag = 1; ans = fv; break; } for(int i = 0; i < 4; i++) {//东南西北四个方向 fx = temp.x + dir[i][0],fy = temp.y + dir[i][1],fz = temp.z,fv = temp.val; if(fx >=0 && fx < r && fy >=0 && fy < c && (s[fz][fx][fy] == '.' || s[fz][fx][fy] == 'E') && !vis[fz][fx][fy]) { vis[fz][fx][fy] = 1; q.push(node(fx,fy,fz,fv+1));//每走一步,花费加1 } } fx = temp.x, fy = temp.y,fv = temp.val; fz = temp.z+1; if(fz >=0 && fz < l&&(s[fz][fx][fy] == '.' || s[fz][fx][fy] == 'E')&& !vis[fz][fx][fy]) {//向上 vis[fz][fx][fy] = 1; q.push(node(fx,fy,fz,fv+1)); } fz = temp.z-1; if(fz >=0 && fz < l&&(s[fz][fx][fy] == '.' || s[fz][fx][fy] == 'E') && !vis[fz][fx][fy]) {//向下 vis[fz][fx][fy] = 1; q.push(node(fx,fy,fz,fv+1)); } } } int main() { while(cin >> l >> r >> c &&l&&r&&c) { mem(vis,0); flag = 0; for(int i = 0; i < l; i++) { for(int j = 0 ; j < r; j++) { cin >> s[i][j]; } } for(int i = 0; i < l; i++) { for(int j = 0; j < r; j++) { for(int k = 0; k < c; k++) { if(s[i][j][k] == 'S'){//找到起点开始搜 bfs(i,j,k); break; } } } } if(flag) cout << "Escaped in "<< ans << " minute(s)." <<endl; else cout << "Trapped!" << endl; } return 0; }