繁体   English   中英

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

[英]StackOverflow error due to recursion in Java

我正在尝试使用递归方法来解决由 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;
   }
}

在过去的几个小时里,我一直被这个错误所困扰,任何帮助将不胜感激。

我认为没有这样的错误(不是我能看到的),但是您递归的方式太多导致了这个问题。 我不确定您在程序中输入了哪些值,但是我注意到使用以下参数初始化上述程序时存在的问题:

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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM