能够做到这里,就说明有一定的深搜(dfs)、广搜的基础(bfs),dfs用来找到所有的情况,它和bfs的区别就在于此,bfs也可以找到所有情况,但是,第一种永远是最短的,因为是按照称述来计数的。
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!");
}
}
9.9 分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复