Rat in a maze (only one test case working)

import java.util.*;
public class Main {
static boolean ans = false;
static boolean p = false;
static Scanner sc = new Scanner(System.in);
public static char[][] insert(int n, int m) {
char[][] board = new char[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
board[i][j] = sc.next().charAt(0);
}
}
return board;
}
public static void display2(int[][] result) {
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j]+" “);
}
System.out.println(” ");
}
}

public static void ratMaze(char[][] borad,int[][] result,int row, int col,int n,int m) {
	
	if (row == n-1 && col == m-1) {
		result[row][col] = 1;
		if (!p) {
			display2(result);
			p = true;
			ans = true;
		}
	}
	
	if (row == 0 && col == m-1) {
		
	}
	
	if (row == n || row < 0 || col == m || col < 0 || borad[row][col] == 'X') {
		return;
	}
	
	result[row][col] = 1;
	ratMaze(borad, result, row, col+1, n, m);
	ratMaze(borad, result, row+1, col, n, m);
	result[row][col] = 0;
	
	return ;
}

public static void main(String[] args) {		
	int N = sc.nextInt(); 
	int M = sc.nextInt();
	char[][] board = insert(N, M);
	int[][] result = new int[N][M]; 
	ratMaze(board, result, 0, 0, N, M);
	if (!ans) {
		System.out.println("-1");
	}
}

}

@10vaibhavsinghnegi,
I have corrected your code. There was an error in your insert function. But this code will still give you a TLE on 1 test case. Try to further optimize your approach, if you are not able to, then reply on this thread, I will help you out.

https://ide.codingblocks.com/s/206910 corrected code

i can’t optimize it further pls help me out…
it is working for 0 to 4 test cases but gives a TLS in test case 5

@10vaibhavsinghnegi,
Instead of keeping a global ans variable we return boolean from RatMaze function.

It basically saves recursive queries we might have to deal with even when we have already calculated that we cannot get an answer from that.
https://ide.codingblocks.com/s/206933 Corrected code.

thank you for helping

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.