1

我正在尝试编写递归代码来查找方形网格的所有退出路径,但在 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;
    }

//编辑:下面是主要方法,它显示了我最初所说的逃逸。

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

4 回答 4

1

这是堆栈溢出错误。由于您在escape(row,col,swamp,escapePath);不更改 for 循环中第一个单元格的状态的情况下重复调用。

我对修复的猜测是改变rowcol

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

row+icol+j

于 2013-10-08T02:46:53.690 回答
0

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

于 2013-10-08T02:45:35.887 回答
0

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

于 2013-10-08T02:49:23.180 回答
-1

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

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

有了这个:

escapePath+="["+row+","+col+"]";
于 2013-10-08T02:31:34.713 回答