未知的Java递归错误

时间:2013-10-08 02:23:44

标签: java recursion

我正在尝试编写递归代码来查找方形网格的所有退出路径,但是我收到了一些错误 在Project4.escape(Project4.java:41) 我不知道错误是什么,因为以下行:

在Project4.escape(Project4.java:41)

经常重复

以使错误消息不可见。请帮我找到问题,并解决它。以下是我的逃避方法。

private static void escape(int row, int col, int[][] swamp,String escapePath)
    {
        if (row == swamp.length || row==0 || col == 0 || col == swamp.length)
        {
            //winner
            System.out.println(escapePath);

        }
        else
        {
            for (int i = -1; i < 2; i++)
            {
                for (int j=-1;j<2;j++)
                {
                    if (row+i>=0 && j+col>=0 && row+i<swamp.length && col+j<swamp.length &&
                    swamp[row + i][col + j] == 1)
                    {
                        escapePath+="["+row+","+col+"]";
                        swamp[row][col]=2;
                        escape(row,col,swamp,escapePath);
                    }
                }
            }
        }
        swamp[row][col]=1;
    }

//编辑:现在接下来的是主要方法,它显示了我最初调用escape的方法。

public static void main(String[] args) throws Exception
    {
        int[] dropInPt = new int[2]; // row and col will be on the 2nd line of input file;
        int[][] swamp = loadSwamp( args[0], dropInPt ); //returns an 8 by 8 grid of 0s and 1s and fills dropInPt with 1s
        int row=dropInPt[0], col = dropInPt[1];
        printSwamp(          "\n   SWAMP: dropped in at: ["+row+","+col+"]\n",swamp );
        System.out.println("\n   ESCAPE PATHS:\n");


        String escapePath = "["+dropInPt[0]+","+dropInPt[1]+"]";
        escape(row,col,swamp,escapePath);


    }

4 个答案:

答案 0 :(得分:1)

这是stackoverflow错误。因为你在不改变for循环中第一个单元格状态的情况下反复调用escape(row,col,swamp,escapePath);

我对解决方法的猜测是更改

中的rowcol
swamp[row][col]=2;
escape(row,col,swamp,escapePath);

row+icol+j

答案 1 :(得分:0)

在我看来,row和col永远不会被重新分配 - 每次函数重复时,它都在相同的输入上运行。递归永远不会结束,导致堆栈溢出错误。

答案 2 :(得分:0)

由于一次又一次地执行相同的递归而导致的可能的堆栈错误。在内部嵌套的for循环中,您不需要计算i==0 and j==0何时一次又一次地计算相同的点。

答案 3 :(得分:-1)

也许问题出现了,因为你的引号中有“col”。尝试替换它:

escapePath+="["+row+","+"col"+"]";

用这个:

escapePath+="["+row+","+col+"]";