Java迷宫解决问题



所以我被要求解决递归 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;
}

}

您在 1 处缺少引号

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

应该是

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

和代表数字 1 的字符在 Java(以及任何其他静态类型语言中)是两个不同的东西,所以你不能检查它们是否像这样相等。

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

使用以下代码:

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

最新更新