简体   繁体   中英

Java maze solving issue

so I've been asked to solve a maze in a recursive java function, but I stumble into an issue that the recursive function doesnt seem to switch the correct path into '*'.

Any help would be appreciated.

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

}

You're missing quotes around the 1 at

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

should be

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

The number 1 and the character representing the number 1 are two different things in Java (and in any other statically typed language), so you can't check if they're equal like that.

I doubt that the code will find all paths then though, since you don't seem to be searching left and up at all.

Use this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM