Doubt-Rat In A Maze

Please correct my code and also please tell me where I went wrong.

public static boolean printRatPath(char [][]maze,int row,int col,int [][]sol)

{
	if(row==maze.length-1 && col==maze[0].length-1)
	{
		sol[row][col]=1;
		return true;
	}
	if(row>=maze.length || col>=maze[0].length || maze[row][col]=='X')
	{
		return false;
	}
	sol[row][col]=1;

	printRatPath(maze,row,col+1,sol);
	printRatPath(maze,row+1,col,sol);

	sol[row][col]=0;
	return false;
}

public static void displayArr(int [][]sol,int m,int n)
{
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			System.out.print(sol[i][j]);
		}
		System.out.println();
	}
}

public static void main(String[] args) {
	Scanner sc=new Scanner(System.in);
	int m=sc.nextInt();
	int n=sc.nextInt();
	char [][]maze=new char[m][n];
	for(int i=0;i<m;i++)
	{
		for(int j=0;j<n;j++)
		{
			maze[i][j]=sc.next().charAt(0);
		}
	}
	int [][]sol=new int [m][n];
	if(printRatPath(maze,0,0,sol))
	{
		displayArr(sol,m,n);
	}
	else
	{
		System.out.println(-1);
	}
}

}

Your code had 2 errors
1-> There was an error in the input format. Play close attention to the input format. (We are provided with a string for every row)
2-> You were not catching the result of these calls
printRatPath(maze,row,col+1,sol);
printRatPath(maze,row+1,col,sol);

You need to store the result for these calls and return true if a path exist for this call.
Rest the logic of the code looks good.

I have updated your code and added comments at the necessary places.
You can refer to it here.(Though I’d suggest you to try correcting your code yourself first :slight_smile: )

Also, please share the code using the onlline IDE from next time onwards. It’s easier to debug it that way.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.