-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRatInAMaze.java
More file actions
62 lines (52 loc) · 1.06 KB
/
RatInAMaze.java
File metadata and controls
62 lines (52 loc) · 1.06 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
51
52
53
54
55
56
57
58
59
60
61
62
package allproblems;
public class RatInAMaze {
public static boolean ratInAMaze(int maze[][])
{
int n = maze.length; //row 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;
//checking if the cell is a valid cell or not
if(i<0 || i>=n || j<0 || j>=n || maze[i][j]==0 || path[i][j]==1)
{
return false;
}
//include cell in current path
path[i][j]=1;
//destination cell
if(i==n-1 && j==n-1)
{
return true;
}
//explore 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,1,0},{1,1,1}};
boolean pathpossible = ratInAMaze(maze);
System.out.println("Path exists?: "+pathpossible);
}
}