You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//A Maze is given as N*N binary matrix of blocks where source block is the upper left most block(maze[0][0]) and destination block is lower rightmost block (maze[N-1][N-1]).
3
+
//A rat starts from source and has to reach the destination.
4
+
//The rat can move only in two directions: left, right, down, up.
5
+
//In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination.
6
+
//Backtracking - Solving one piece at a time, and removing those solutions that fail to satisfy the constraints of the problem at any point of time is the process of backtracking.
7
+
publicclassRat_In_A_Maze {
8
+
9
+
// Size of the maze
10
+
staticintN;
11
+
12
+
//function to print solution matrix
13
+
voidprintSolution(intsol[][])
14
+
{
15
+
for (inti = 0; i < N; i++) {
16
+
for (intj = 0; j < N; j++)
17
+
System.out.print(
18
+
" " + sol[i][j] + " ");
19
+
System.out.println();
20
+
}
21
+
}
22
+
23
+
booleanisSafe(
24
+
intmaze[][], intx, inty)
25
+
{
26
+
// if x, y outside maze return false directly
27
+
return (x >= 0 && x < N && y >= 0
28
+
&& y < N && maze[x][y] == 1);
29
+
}
30
+
31
+
booleansolveMaze(intmaze[][])
32
+
{
33
+
intsol[][] = newint[N][N];
34
+
35
+
if (solveMazeUtil(maze, 0, 0, sol) == false) {
36
+
//No solution possible
37
+
System.out.print("Solution doesn't exist");
38
+
returnfalse;
39
+
}
40
+
41
+
printSolution(sol);
42
+
returntrue;
43
+
}
44
+
45
+
46
+
booleansolveMazeUtil(intmaze[][], intx, inty,
47
+
intsol[][])
48
+
{
49
+
// if x, y is destination return true
50
+
if (x == N - 1 && y == N - 1
51
+
&& maze[x][y] == 1) {
52
+
sol[x][y] = 1;
53
+
returntrue;
54
+
}
55
+
56
+
// Check if maze[x][y] is valid
57
+
if (isSafe(maze, x, y) == true) {
58
+
// Check if the current block is already visited.
59
+
if (sol[x][y] == 1)
60
+
returnfalse;
61
+
62
+
// mark x, y as visited
63
+
sol[x][y] = 1;
64
+
if (solveMazeUtil(maze, x + 1, y, sol))
65
+
returntrue;
66
+
if (solveMazeUtil(maze, x, y + 1, sol))
67
+
returntrue;
68
+
if (solveMazeUtil(maze, x - 1, y, sol))
69
+
returntrue;
70
+
if (solveMazeUtil(maze, x, y - 1, sol))
71
+
returntrue;
72
+
73
+
sol[x][y] = 0;//un-mark the maze index so that other paths can be explored
0 commit comments