题目链接:https://www.acwing.com/problem/content/description/1098/
题解:
三维的一个BFS,visit数组和结果数组合并,一定要记得每次BFS清空visit数组即可
AC代码(Java):
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* @author: doudou
* @date: Created in 2020/4/28
* @description:
* @version: 1.0
*/
public class Main {
private static char[][][] a = new char[105][105][105];
private static int[][][] st = new int[105][105][105];
private static int[] zz = {1, -1, 0, 0, 0, 0};
private static int[] zx = {0, 0, -1, 1, 0, 0};
private static int[] zy = {0, 0, 0, 0, 1, -1};
private static int l, r, c;
public static int bfs(Three start, Three end) {
Queue<Three> q = new LinkedList<>();
q.add(start);
for (int i = 0;i < l;i++)
for (int j = 0; j < r; j++)
for (int k = 0;k < c; k++) st[i][j][k] = -1;
st[start.z][start.x][start.y] = 0;
while (!q.isEmpty()) {
Three now = q.poll();
for (int i = 0; i < 6; i++) {
int futurez = now.z + zz[i];
int futurex = now.x + zx[i];
int futurey = now.y + zy[i];
if (futurez < 0 || futurez >= l || futurex < 0 || futurex >= r || futurey < 0 || futurey >= c) continue;
if (st[futurez][futurex][futurey] != -1) continue;
if (futurez == end.z && futurex == end.x && futurey == end.y) return st[now.z][now.x][now.y] + 1;
if (a[futurez][futurex][futurey] == '#') continue;
q.offer(new Three(futurez,futurex,futurey));
st[futurez][futurex][futurey] = st[now.z][now.x][now.y] + 1;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
l = sc.nextInt();
r = sc.nextInt();
c = sc.nextInt();
if (l == 0 && r == 0 && c == 0) break;
sc.nextLine();
Three start = null, over = null;
for (int i = 0; i < l; i++) {
for (int j = 0; j < r; j++) {
char[] chars = sc.nextLine().toCharArray();
a[i][j] = chars;
for (int k = 0; k < chars.length; k++) {
if (chars[k] == 'S') {
start = new Three(i, j, k);
}
if (chars[k] == 'E') {
over = new Three(i, j, k);
}
}
// System.out.println(Arrays.toString(chars));
}
sc.nextLine();
}
int res = bfs(start, over);
if (res != -1 ) {
System.out.println("Escaped in "+res+" minute(s).");
}else {
System.out.println("Trapped!");
}
}
}
}
class Three {
int z, x, y;
Three(int z, int x, int y) {
this.z = z;
this.x = x;
this.y = y;
}
}