[英]Maze solver java
我需要为APCS编写一个迷宫求解程序,其中涉及一个基于文本的1和0矩阵。 我必须编写代码来查找从坐标0,0到右侧任意位置的路径(如果有)。 这是我到目前为止的
public class Maze {
private int[][] maze;
private int sizes = 0;
private boolean[][] checked;
public Maze(int size, String line) {
checked = new boolean[size][size];
sizes = size;
out.println(sizes - 1);
Scanner joe = new Scanner(line);
maze = new int[size][size];
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
maze[x][y] = joe.nextInt();
}
}
}
public boolean hasExitPath(int r, int c) {
boolean solved = false;
boolean wall = false;
if (r == sizes - 1) {
solved = true;
return solved;
}
maze[r][c] = 2;
if (maze[r + 1][c] == 1) {
out.println("down");
hasExitPath(r + 1, c);
}else if (maze[r][c + 1] == 1) {
out.println("left");
hasExitPath(r, c + 1);
}else if (maze[r - 1][c] == 1) {
out.println("up");
hasExitPath(r - 1, c);
}else if (maze[r][c - 1] == 1) {
out.println("right");
hasExitPath(r, c - 1);
}
System.out.println(r + " " + c);
return solved;
}
public String toString() {
String output = "";
for (int y = 0; y < sizes; y++) {
for (int x = 0; x < sizes; x++) {
output = output + maze[y][x];
}
output = output + "\n";
}
return output;
}
}
这是主班
public class MazeRunner {
public static void main(String args[]) throws IOException {
Scanner mazeinfo = new Scanner(new File("maze.dat"));
int size = mazeinfo.nextInt();
mazeinfo.nextLine();
String b = mazeinfo.nextLine();
Maze m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
size = mazeinfo.nextInt();
mazeinfo.nextLine();
b = mazeinfo.nextLine();
m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
size = mazeinfo.nextInt();
mazeinfo.nextLine();
b = mazeinfo.nextLine();
m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
size = mazeinfo.nextInt();
mazeinfo.nextLine();
b = mazeinfo.nextLine();
m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
size = mazeinfo.nextInt();
mazeinfo.nextLine();
b = mazeinfo.nextLine();
m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
size = mazeinfo.nextInt();
mazeinfo.nextLine();
b = mazeinfo.nextLine();
m = new Maze(size, b);
out.println(m);
out.println(m.hasExitPath(0, 0));
}
}
这是需要解决的迷宫图像
https://drive.google.com/file/d/0BzE3Cu7SjRlNdzRHYjM4UzZkY00/view?usp=sharing
我在hasExitPath方法中添加了一堆调试代码,以帮助我了解发生了什么。 每当我运行程序时,它似乎就无法追踪迷宫。 我需要在此程序中添加什么?
调用hasExitPath(r , c)
将始终返回false
,除非r == size - 1
为true。 由于从r == 0
,并且size > 0
为true,因此代码始终以false
结果。 采用
if(hasExitPath(r + 1, c))
return true;
而不是简单地调用hasExitPath(r + 1, c);
,以解决此问题(与对hasExitPath(r , c)
所有其他递归调用相同)。
我建议不要使用递归方法,如果迷宫变得足够大,则可能会出现堆栈溢出问题。 我建议您根据行进的方向进行操作,然后根据到达交叉路口或死胡同重新评估方向。 我可以给您提供一些链接的链接,这些链接可以解决迷宫问题,但不能使用2D数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.