我正在尝试使用递归方法来解决Java中由1和0的int数组表示的迷宫 . wasHere []检查方法是否已经解析了该特定坐标集,correctPath []记录了迷宫的答案路径;它们都被初始化,每个索引都是假的 .
import java.awt.Point;
class mazeSolver{
int[][] maze;
int startX, startY;
int endX, endY;
int width, height;
boolean[][] wasHere, correctPath;
mazeSolver(int[][] m, int sX,int sY,int nX,int nY){
maze = m;
width = maze[0].length;
height = maze.length;
startX = sX;
startY = sY;
endX = nX;
endY = nY;
System.out.println("Height: " + height + "\t Width: " + width);
correctPath = new boolean[height][width];
wasHere = new boolean[height][width];
for (int row = 0; row < maze.length; row++)
for (int col = 0; col < maze[row].length; col++){
wasHere[row][col] = false;
correctPath[row][col] = false;
}
solveMaze(startX,startY);
}
public boolean solveMaze(int x, int y){
boolean solvable = recursiveSolve(x,y);
return solvable;
}
private boolean recursiveSolve(int x, int y){ //1s are walls, 0s are free space
if (x == endX && y == endY)
return true;
if (wasHere[y][x] || maze[y][x] == 1)
return false;
wasHere[y][x] = true;
if (y < height-1){
if (solveMaze(x,y+1))
return true;
}
if (y > 0){
if (solveMaze(x,y-1))
return true;
}
if (x > 0){
if (solveMaze(x-1,y))
return true;
}
if (x < width-1){
if (solveMaze(x+1,y))
return true;
}
return false;
}
public int[][] getSolvedMaze(){
for(int y = 0; y < height; y++)
for (int x = 0; x< width; x++)
if(correctPath[y][x])
maze[y][x] = 2;
return maze;
}
}
在过去的几个小时里,我一直坚持这个错误,任何帮助将不胜感激 .
1 回答
我认为没有这样的错误(不是我能看到的),但是你的回复方式过多导致了这个问题 . 我不确定你为这个程序提供了什么 Value ,但我能够注意到用这些参数初始化上述程序的问题:
所以为了运行你的程序,我增加了堆栈大小 . 您可以在运行程序时将以下参数提供给JVM:
-Xss258m
这个堆栈大小能够容纳1000个大小的数组 . 我没有太多时间来测试其他尺寸 .