forked from riya2001-cloud/java-hacktober
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRatInAMaze.java
62 lines (46 loc) · 1.39 KB
/
RatInAMaze.java
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
51
52
53
54
55
56
57
58
59
60
61
62
/*Question: In this problem, there is a given maze of size N x N. The source and the destination location is top-left cell and bottom right cell respectively.
Some cells are valid to move and some cells are blocked.
If one rat starts moving from start vertex to destination vertex, we have to find that is there any way to complete the path,
if it is possible then mark the correct path for the rat.*/
public class RatInAMaze {
public static boolean ratInAMaze(int maze[][]) {
int n=maze.length;
int path[][]= new int[n][n];
return solveMaze(maze, 0, 0, path);
}
public static boolean solveMaze(int maze[][],int i,int j,int[][] path) {
int n=maze.length;
//Check if i,j cell is valid or not
if(i<0 || i>=n || j<0 || j>=n || maze[i][j]==0 || path[i][j]==1) {
return false;
}
//Include the cell in current path
path[i][j]=1;
if(i==n-1 && j==n-1) {
return true;
}
//Explore further in all directions
//top
if(solveMaze(maze, i-1, j, path)) {
return true;
}
//right
if(solveMaze(maze, i, j+1, path)) {
return true;
}
//Down
if(solveMaze(maze, i+1, j, path)) {
return true;
}
//Left
if(solveMaze(maze, i, j-1, path)) {
return true;
}
return false;
}
public static void main(String[] args) {
int maze[][]= {{1,1,0},{1,0,1},{1,1,1}};
boolean pathPossible =ratInAMaze(maze);
System.out.println(pathPossible);
}
}