信息学奥赛一本通T1248-Dungeon Master - C语言网 (dotcpp.com)
能够做到这里,就说明有一定的深搜(dfs)、广搜的基础(bfs),dfs用来找到所有的情况,它和bfs的区别就在于此,bfs也可以找到所有情况,但是,第一种永远是最短的,因为是按照称述来计数的。
![](https://i-blog.csdnimg.cn/blog_migrate/91d5136808d1f5c0dbaa5ae4b6f90923.png)
深度搜索主要拿来找全部可能性:
import java.util.*;
public class Main {
static class ZuoBiao {//存放坐标zxy
int z;
int x;
int y;
public ZuoBiao(int z, int x, int y) {
super();
this.z = z;
this.x = x;
this.y = y;
}
public ZuoBiao() {
}
}
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int z = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
while(z!=0&&y!=0&&z!=0) {
f(z,x,y);
z = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
}
// for (int i = 0; i < z; i++) {//三维数组储存完毕
// for (int j = 0; j < x; j++) {
// for (int k = 0; k < y; k++) {
// System.out.print(arr[i][j][k]);
// }
// System.out.println();
// }
// System.out.println("*****");
// }
}
private static void f(int z,int x,int y) {
// TODO Auto-generated method stub
ZuoBiao qiDian = new ZuoBiao();
char[][][] arr = new char[z][x][y];
int[][][] chek = new int[z][x][y];//记录走过的地方,不再走了
for (int i = 0; i < z; i++) {
for (int j = 0; j < x; j++) {
char[] charArray = sc.next().toCharArray();
for (int k = 0; k < y; k++) {
if (arr[i][j][k] == 'S') {
qiDian.z = i;
qiDian.x = j;
qiDian.y = k;
chek[i][j][k] = 1;
}
arr[i][j][k] = charArray[k];
}
}
}
Queue<ZuoBiao> dui = new LinkedList<ZuoBiao>();
dui.offer(qiDian);
int cont = 0;
while (!dui.isEmpty()) {
int size = dui.size();
cont++;
for (int i = 0; i < size; i++) {
ZuoBiao poll = dui.poll();
int z1 = poll.z;
int x1 = poll.x;
int y1 = poll.y;
//然后就是六个方位找
if (arr[z1][x1][y1] == 'E') {
System.out.println("Escaped in " + (cont - 1) + " minute(s).");
return;
}
if (x1 - 1 >= 0 && arr[z1][x1 - 1][y1] != '#' && chek[z1][x1 - 1][y1] != 1) {// 上
chek[z1][x1 - 1][y1] = 1;
dui.offer(new ZuoBiao(z1, x1 - 1, y1));
}
if (y1 + 1 < y && arr[z1][x1][y1 + 1] != '#' && chek[z1][x1][y1 + 1] != 1) {// 右
chek[z1][x1][y1 + 1] = 1;
dui.offer(new ZuoBiao(z1, x1, y1 + 1));
}
if (x1 + 1 < x && arr[z1][x1 + 1][y1] != '#' && chek[z1][x1 + 1][y1] != 1) {// 下
chek[z1][x1 + 1][y1] = 1;
dui.offer(new ZuoBiao(z1, x1 + 1, y1));
}
if (y1 - 1 >= 0 && arr[z1][x1][y1 - 1] != '#' && chek[z1][x1][y1 - 1] != 1) {// 左
chek[z1][x1][y1 - 1] = 1;
dui.offer(new ZuoBiao(z1, x1, y1 - 1));
}
if (z1 + 1 < z && arr[z1 + 1][x1][y1] != '#' && chek[z1 + 1][x1][y1] != 1) {// 下一层
chek[z1 + 1][x1][y1] = 1;
dui.offer(new ZuoBiao(z1 + 1, x1, y1));
}
if (z1 - 1 >= 0 && arr[z1 - 1][x1][y1] != '#' && chek[z1 - 1][x1][y1] != 1) {// 上一层
chek[z1 - 1][x1][y1] = 1;
dui.offer(new ZuoBiao(z1 - 1, x1, y1));
}
}
}
System.out.println("Trapped!");//所有层数都找了一遍,屁都没有,死路
}
}