不放题目了,挂上链接吧,POJ - 2251
这是一道三维地图的最短路问题,最短路嘛就是要用bfs,dfs回溯在这里估计要超时了,回溯太费时间了,指数级的复杂度。
这里我们用
ax[6] = {1, -1, 0, 0, 0, 0};
ay[6] = {0, 0, 1, -1, 0, 0};
az[6] = {0, 0, 0, 0, 1, -1};
记录六个方向的坐标变化,接下来就是比较low的bfs板子了
//Powered by CK
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 50;
const int ax[6] = {0, 0, 0, 0, 1, -1};
const int ay[6] = {-1, 1, 0, 0, 0, 0};
const int az[6] = {0, 0, -1, 1, 0, 0};
int maze[N][N][N], n, m, p, sx, sy, sz, flag;
struct point {
int x, y, z, step;
point(int a, int b, int c, int d) : x(a), y(b), z(c), step(d) {}
};
queue<point> q;
bool judge(int x, int y, int z) {
if(!maze[x][y][z] && x >= 0 && x < n && y >= 0 && y < m && z >= 0 && z < p)
return true;
return false;
}
void bfs() {
while(!q.empty()) {
point temp = q.front();
q.pop();
// cout << temp.step << endl;
if(temp.x == sx && temp.y == sy && temp.z == sz) {
printf("Escaped in %d minute(s).
", temp.step);
return ;
}
for(int i = 0; i < 6; i++) {
int tempx = temp.x + ax[i];
int tempy = temp.y + ay[i];
int tempz = temp.z + az[i];
if(judge(tempx, tempy, tempz)) {
q.push(point(tempx, tempy, tempz, temp.step + 1));
maze[tempx][tempy][tempz] = 1;
}
}
}
puts("Trapped!");
}
int main() {
char c;
int x, y, z;
while(cin >> n >> m >> p && n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++)
for(int k = 0; k < p; k++) {
cin >> c;
if(c == 'S') x = i, y = j, z = k, maze[i][j][k] = 0;
else if(c == 'E') sx = i, sy = j, sz = k, maze[i][j][k] = 0;
else if(c == '.') maze[i][j][k] = 0;
else maze[i][j][k] = 1;
}
getchar();
}
while(!q.empty()) q.pop();
q.push(point(x, y, z, 0));
maze[x][y][z] = 1;
bfs();
}
return 0;
}