由于Java中的递归导致的StackOverflow错误

时间:2015-06-13 00:28:39

标签: java recursion stack-overflow maze

我尝试使用递归方法来解决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 个答案:

答案 0 :(得分:1)

我认为没有这样的错误(不是我能看到的)但是你提出的方式过多导致了这个问题。我不确定你对这个程序有什么价值,但我能够注意到用这些参数初始化上述程序的问题:

mazeSolver MazeSolver = new  mazeSolver(new int [100][100], 0, 0, 100,100);

所以为了运行你的程序,我增加了堆栈大小。您可以在运行程序时将以下参数提供给JVM:-Xss258m

此堆栈大小能够容纳1000个大小的数组。我没有太多时间测试其他尺寸。

mazeSolver MazeSolver = new  mazeSolver(new int [1000][1000], 0, 0, 1000,1000);