Skip to content

Commit ccc88df

Browse files
committed
Added rat in a maze backtracking problem
1 parent add4d35 commit ccc88df

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
2+
//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+
public class Rat_In_A_Maze {
8+
9+
// Size of the maze
10+
static int N;
11+
12+
//function to print solution matrix
13+
void printSolution(int sol[][])
14+
{
15+
for (int i = 0; i < N; i++) {
16+
for (int j = 0; j < N; j++)
17+
System.out.print(
18+
" " + sol[i][j] + " ");
19+
System.out.println();
20+
}
21+
}
22+
23+
boolean isSafe(
24+
int maze[][], int x, int y)
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+
boolean solveMaze(int maze[][])
32+
{
33+
int sol[][] = new int[N][N];
34+
35+
if (solveMazeUtil(maze, 0, 0, sol) == false) {
36+
//No solution possible
37+
System.out.print("Solution doesn't exist");
38+
return false;
39+
}
40+
41+
printSolution(sol);
42+
return true;
43+
}
44+
45+
46+
boolean solveMazeUtil(int maze[][], int x, int y,
47+
int sol[][])
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+
return true;
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+
return false;
61+
62+
// mark x, y as visited
63+
sol[x][y] = 1;
64+
if (solveMazeUtil(maze, x + 1, y, sol))
65+
return true;
66+
if (solveMazeUtil(maze, x, y + 1, sol))
67+
return true;
68+
if (solveMazeUtil(maze, x - 1, y, sol))
69+
return true;
70+
if (solveMazeUtil(maze, x, y - 1, sol))
71+
return true;
72+
73+
sol[x][y] = 0;//un-mark the maze index so that other paths can be explored
74+
return false;
75+
}
76+
77+
return false;
78+
}
79+
80+
public static void main(String args[])
81+
{
82+
Rat_In_A_Maze rat = new Rat_In_A_Maze();
83+
int maze[][] = { { 1, 1, 1, 1 },
84+
{ 1, 1, 0, 1 },
85+
{ 0, 1, 0, 1 },
86+
{ 1, 1, 0, 1 } };
87+
88+
N = maze.length;
89+
rat.solveMaze(maze);
90+
}
91+
}
92+
93+
//Time complexity - O(2^(n*n))

0 commit comments

Comments
 (0)