输入样例:
3 4 5
S....
.###.
.##..
###.#
#####
#####
##.##
##...
#####
#####
#.###
####E
1 3 3
S##
#E#
###
0 0 0
输出样例:
Escaped in 11 minute(s).
Trapped!
解题思路:
是献给阿尔吉侬的花束的三维扩展,只需要在偏移量上多加两个判断方向,再把二维数组换成三维数组即可。
Java代码:
import java.io.*;
import java.util.*;
public class Main {
static int l, r, c;
static int [][][]map;
static boolean [][][]vis;
static Point start;
static Point end;
static int []dz = {-1, 1, 0, 0, 0, 0};//偏移量
static int []dx = {0, 0, -1, 0, 1, 0};
static int []dy = {0, 0, 0, 1, 0, -1};
static class Point{
int z, x, y;
int step;
public Point(int z, int x, int y, int step) {
this.z = z;
this.x = x;
this.y = y;
this.step = step;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
String str = br.readLine();
if(str.equals("0 0 0")) break;
String[] split = str.split(" ");
l = Integer.parseInt(split[0]);
r = Integer.parseInt(split[1]);
c = Integer.parseInt(split[2]);
map = new int[l][r][c];
vis = new boolean[l][r][c];
for(int i = 0; i < l; i++) {
for(int j = 0; j < r; j++) {
String s = br.readLine();
for(int k = 0; k < c; k++) {
map[i][j][k] = s.charAt(k);
if(map[i][j][k] == 'S') start = new Point(i, j, k, 0);
if(map[i][j][k] == 'E') end = new Point(i, j, k, 0);
if(map[i][j][k] != '#') vis[i][j][k] = true;
}
}
br.readLine();
}
bfs();
}
}
public static void bfs() {
Queue<Point> qu = new LinkedList<>();
qu.add(start);
while(!qu.isEmpty()) {
Point p = qu.poll();
vis[p.z][p.x][p.y] = false;
if(p.z == end.z && p.x == end.x && p.y == end.y) {
System.out.printf("Escaped in %d minute(s).\n", p.step);
return;
}
for(int i = 0; i < 6; i++) {
int z = p.z + dz[i], x = p.x + dx[i], y = p.y + dy[i];
if(z < 0 || z >= l || x < 0 || x >= r || y < 0 || y >= c) continue;
if(map[z][x][y] != '#' && vis[z][x][y]) {
qu.add(new Point(z, x, y, p.step + 1));
vis[z][x][y] = false;
}
}
}
System.out.println("Trapped!");
}
}