-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRatInADeadMazeFour.java
More file actions
38 lines (30 loc) · 1.13 KB
/
RatInADeadMazeFour.java
File metadata and controls
38 lines (30 loc) · 1.13 KB
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
package BackTracking;
public class RatInADeadMazeFour {
private static void print(int sr, int sc, int er, int ec, String s, int[][] maze) {
if (sr < 0 || sc < 0 || sc > ec || sr > er || maze[sr][sc] == 0)
return;
if (sr == er && sc == ec) {
System.out.println(s);
return;
}
maze[sr][sc] = 0;
print(sr, sc + 1, er, ec, s + "R", maze);
print(sr + 1, sc, er, ec, s + "D", maze);
print(sr, sc - 1, er, ec, s + "L", maze);
print(sr - 1, sc, er, ec, s + "U", maze);
maze[sr][sc] = 1;
}
/*
* The rat can move through the maze in four directions, he has to move only if it is 1, if 0 can't move.
* We could have also created an isVisited 2-D matrix, but that would consume more memory.
* We have to apply a check because the rat would otherwise loop over the matrix.
*/
public static void main(String[] args) {
int rows = 3;
int cols = 4;
int[][] maze = {{1, 0, 1, 1},
{1, 1, 1, 1,},
{1, 1, 0, 1}};
print(0, 0, rows - 1, cols - 1, "", maze);
}
}