-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rat_in_a_maze || Rat Chases its cheese
47 lines (44 loc) · 1.41 KB
/
Rat_in_a_maze || Rat Chases its cheese
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;
public class Rat_in_a_maze{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.nextLine(); // Consume newline character
char[][] maze = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.nextLine();
for (int j = 0; j < m; j++) {
maze[i][j] = s.charAt(j);
}
}
int[][] ans = new int[n][m];
printPath(maze, 0, 0, ans);
}
public static void printPath(char[][] maze, int cr, int cc, int[][] ans) {
if (cr == maze.length - 1 && cc == maze[0].length - 1) {
display(ans);
return;
}
if (cr < 0 || cr >= maze.length || cc < 0 || cc >= maze[0].length || maze[cr][cc] == 'X') {
return;
}
int[] r = {0, -1, 0, 1};
int[] c = {1, 0, -1, 0};
maze[cr][cc] = 'X';
ans[cr][cc] = 1;
for (int i = 0; i < c.length; i++) {
printPath(maze, cr + r[i], cc + c[i], ans);
}
maze[cr][cc] = '0';
ans[cr][cc] = 0;
}
public static void display(int[][] ans) {
for (int i = 0; i < ans.length; i++) {
for (int j = 0; j < ans[0].length; j++) {
System.out.print(ans[i][j] + " ");
}
System.out.println();
}
}
}