Java递归迷宫在没有堆栈溢出的位置之间振荡

时间:2015-11-10 03:37:23

标签: java recursion branch

我有一个静态方法getPath( int r, int c, int[][] maze, String path ),它返回解决迷宫的路径的字符串值。我已经阅读了关于递归迷宫的所有其他帖子,但我已经解决了这个问题好几天了,我无法弄清楚为什么它不起作用。使用调试器无助于找到解决方案。如果有人能找到答案请分享。以下代码适用于某些地图,但它不适用于某个特定地图:

int[][] maze = { {  0, 0,97, 0, 0, 3, 0, 0, 0, 1 },
                 {  0,99, 0,99,99,99, 0,99,99,99 },
                 {  0, 0,99, 0,99, 0, 0, 0, 0, 0 },
                 { 99,99,99,99,99,99,99,99,99, 0 },
                 { 99, 8,99, 0, 0, 0, 5, 0,99, 0 },
                 { 99, 0,99, 0,99,99,99, 0,99, 0 },
                 {  0, 7, 0, 0, 0, 0,99, 0,99, 0 },
                 {  0,99,99,99,99,99,99, 0, 0, 0 },
                 {  0, 2, 1, 0,99, 0, 0,99,99, 4 },
                 {  0,99,99, 0, 0, 0, 0,98,99, 0 } };

以下是代码:

public static String getPath( int r, int c, int[][] maze, String path ) { 

    if( maze[r][c] == 98 ) { return path; } // base case: solution

    maze[r][c] = 11; // marks current position as visited

    if( available( r, c + 1, maze ) // checks if east is available
            && getPath( r, c + 1, maze, path ) != null ) {  // recursive call
        maze[r][c] = 0; // unmarks the current position
        return getPath( r, c + 1, maze, path + "E" ); // recursive return call
    }
    if( available( r + 1, c, maze ) // checks if south is available
            && getPath( r + 1, c, maze, path ) != null ) {
        maze[r][c] = 0;
        return getPath( r + 1, c, maze, path + "S" );
    }
    if( available( r, c - 1, maze) // checks if west is available
            && getPath( r, c - 1, maze, path ) != null ) {
        maze[r][c] = 0;
        return getPath( r, c - 1, maze, path + "W" );
    }
    if( available( r - 1, c, maze ) // checks if north is available
            && getPath( r - 1, c, maze, path ) != null ) {
        maze[r][c] = 0;
        return getPath( r - 1, c, maze, path + "N" );
    }   

    maze[r][c] = 0; // there are no more moves to make

    return  null; // path does not have a solution here
}

public static boolean available( int r, int c, int[][] maze ) {
    return ( r >= 0 && r < maze.length )
            && ( c >= 0 && c < maze[0].length )
            && ( (  maze[r][c] >= 0 && maze[r][c] <= 9 ) || maze[r][c] == 98 );

}

(97是开始,98是结束,99被阻止,0&lt; = i&lt; = 9可用)

0 个答案:

没有答案