For the sample test cast in my code editor its showing the correct answer. But when I run it its showing
Exception in thread “main” java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at RecursionRatInAMaze.main(RecursionRatInAMaze.java:22)
And when I submit it its showing only one test case passed.
import java.util.Scanner;
public class RecursionRatInAMaze
{
private static boolean flag = false;
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int n = Character.getNumericValue(str.charAt(0));
int m = Character.getNumericValue(str.charAt(2));
char [][] maze = new char[n][m];
int [][] ans = new int[n][m];
// char [][] maze = {{‘0’, ‘X’, ‘0’, ‘0’},
// {‘0’, ‘0’, ‘0’, ‘X’},
// {‘0’, ‘0’, ‘X’, ‘0’},
// {‘X’, ‘0’, ‘0’, ‘X’},
// {‘X’, ‘0’, ‘0’, ‘0’}};
for(int i=0; i<maze.length; i++)
{
for(int j=0; j<maze[i].length; j++)
{
maze[i][j] = sc.nextLine().charAt(0);
ans[i][j] = 0;
}
}
solve(maze, ans, 0, 0);
if(flag==false)
System.out.println("1");
}
public static void solve(char [][]maze, int[][]ans, int row, int col)
{
// printAns(ans);
if(flag==true)
return;
if(ans[maze.length-1][maze[0].length-1]==1)
{
flag = true;
// System.out.println("Reached the last row");
printAns(ans);
return;
}
if(row>=maze.length || col>=maze[0].length)
{
return;
}
if(maze[row][col]=='0')
{
ans[row][col]=1;
solve(maze, ans, row, col+1);
solve(maze, ans, row+1, col);
ans[row][col]=0;
}
else if(maze[row][col]=='X')
{
return;
}
}
public static void printAns(int [][]ans)
{
for(int i=0; i<ans.length; i++)
{
for(int j=0; j<ans[i].length; j++)
{
System.out.print(ans[i][j]);
}
System.out.println();
}
}
}