Java迷宫解决问题

时间:2015-01-09 14:28:33

标签: java recursion maze

所以我被要求在递归java函数中解决迷宫,但我偶然发现一个问题,即递归函数似乎没有将正确的路径切换为'*'。

任何帮助都将不胜感激。

 public class Maze 
 {

/**
 * This is only an example,
 * you can change this to test other cases but don't forget to submit the work with this main.
 * @param args
 */
public static void main(String[] args) 
{
    int M = 4;
    int N = 4;
    char[][] maze = {{'1','0','0','0'},{'1','1','0','0'},{'0','1','1','1'},{'0','0','0','1'}};

    if (findPath(maze, 0,0))
        printMaze(maze);
    else
        System.out.println("No solution");
}

private static void printMaze(char[][] maze) 
{
    for (int i = 0; i < maze.length; i++) 
    {
        for (int j = 0; j < maze[0].length; j++) 
        {
            System.out.print(maze[i][j] +" ");
        }
        System.out.println();
    }

}

// you should implement this function
private static boolean findPath(char[][] maze, int i, int j) 
{
    if ((i+1 > maze.length) || (j+1 > maze[i].length))
        return false;
    else
    {
        if (maze[i][j] == 1)
        {
            maze[i][j] = '*';
            if (maze[i+1][j] == 1)
            {
                return findPath(maze, i+1, j);
            }
            if (maze[i][j+1] == 1)
            {
                return findPath(maze, i, j+1);
            }
        }
    }
    return true;
}

}

2 个答案:

答案 0 :(得分:3)

你在

的1附近缺少引号
if (maze[i][j] == 1)

应该是

if (maze[i][j] == '1')

数字1和代表数字1的字符是Java(以及任何其他静态类型语言)中的两个不同的东西,因此您无法检查它们是否与此类似。

我怀疑代码会找到所有路径,因为你似乎没有向左和向上搜索。

答案 1 :(得分:2)

使用此代码:

private static boolean findPath(char[][] maze, int i, int j) 
{
        if (maze[i][j] == 1)
        {
            maze[i][j] = '*';
            if ((i+1 > maze.length && maze[i+1][j] == '1' && findPath(maze, i+1, j))
            {
                return true;
            }
            if ((j+1 > maze[i].length) && maze[i][j+1] == '1' && findPath(maze, i, j+1))
            {
                return true;
            }
            if (i>=1 && maze[i-1][j] == '1' && findPath(maze, i-1,j)){
                return true;
            }
            if(j>=1 && maze[i][j-1] == '1' && findPath(maze, i,j-1)){
                return true;
            }
        }
    return false;
}