-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRatInAMaze.java
More file actions
50 lines (32 loc) · 1.37 KB
/
Copy pathRatInAMaze.java
File metadata and controls
50 lines (32 loc) · 1.37 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
39
40
41
42
43
44
45
46
47
48
49
50
package recursion;
class RatInAMaze {
public static boolean ratInAMaze(int[][] a, boolean[][] isVisited, int row, int col) {
//Base condition when we go out of the matrix length or when i and j is o and when we already visited that position return false
if (row == a.length || col == a.length || a[row][col] == 0 || isVisited[row][col]) {
return false;
}
//base condition for successfully reached to the destination
if (row == a.length - 1 && col == a.length - 1) return true;
//Mark this cell as visited
isVisited[row][col] = true;
///check if path is possible from right
if (ratInAMaze(a, isVisited, row, col + 1)) return true;
//check if path is possible from down
if (ratInAMaze(a, isVisited, row + 1, col)) return true;
//mark this cell as unvisited & backtrack
isVisited[row][col] = false;
return false;
}
public static void main(String[] args) {
//here 0 means block and 1 means there is a path
int[][] a = {
{1, 1, 0, 1},
{1, 1, 1, 1},
{0, 0, 1, 0},
{1, 1, 1, 1},
};
boolean[][] isVisited = new boolean[a.length][a.length];
boolean isPathPossible = ratInAMaze(a, isVisited, 0, 0);
System.out.println(isPathPossible);
}
}