Reputation: 1
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;
}
}
Upvotes: 0
Views: 522
Reputation: 3084
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;
}
Upvotes: 2
Reputation: 3557
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.
Upvotes: 3