Skip to content

Commit ae4029c

Browse files
authored
Create RatMaze.java
this is the solution to the rat in a maze problem form geeksforgeeks
1 parent 714ce2f commit ae4029c

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/* Java program to solve Rat in a Maze problem using backtracking */
2+
3+
public class RatMaze {
4+
5+
// Size of the maze
6+
static int N;
7+
8+
/* A utility function to print solution matrix sol[N][N] */
9+
void printSolution(int sol[][])
10+
{
11+
for (int i = 0; i < N; i++) {
12+
for (int j = 0; j < N; j++)
13+
System.out.print(
14+
" " + sol[i][j] + " ");
15+
System.out.println();
16+
}
17+
}
18+
19+
/* A utility function to check if x, y is valid index for N*N maze */
20+
boolean isSafe(
21+
int maze[][], int x, int y)
22+
{
23+
// if (x, y outside maze) return false
24+
return (x >= 0 && x < N && y >= 0
25+
&& y < N && maze[x][y] == 1);
26+
}
27+
28+
/* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and
29+
prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/
30+
boolean solveMaze(int maze[][])
31+
{
32+
int sol[][] = new int[N][N];
33+
34+
if (solveMazeUtil(maze, 0, 0, sol) == false) {
35+
System.out.print("Solution doesn't exist");
36+
return false;
37+
}
38+
39+
printSolution(sol);
40+
return true;
41+
}
42+
43+
/* A recursive utility function to solve Maze problem */
44+
boolean solveMazeUtil(int maze[][], int x, int y,
45+
int sol[][])
46+
{
47+
// if (x, y is goal) return true
48+
if (x == N - 1 && y == N - 1
49+
&& maze[x][y] == 1) {
50+
sol[x][y] = 1;
51+
return true;
52+
}
53+
54+
// Check if maze[x][y] is valid
55+
if (isSafe(maze, x, y) == true) {
56+
// mark x, y as part of solution path
57+
sol[x][y] = 1;
58+
59+
/* Move forward in x direction */
60+
if (solveMazeUtil(maze, x + 1, y, sol))
61+
return true;
62+
63+
/* If moving in x direction doesn't give solution then Move down in y direction */
64+
if (solveMazeUtil(maze, x, y + 1, sol))
65+
return true;
66+
67+
/* If none of the above movements works then BACKTRACK: unmark x, y as part of solution path */
68+
sol[x][y] = 0;
69+
return false;
70+
}
71+
72+
return false;
73+
}
74+
75+
public static void main(String args[])
76+
{
77+
RatMaze rat = new RatMaze();
78+
int maze[][] = { { 1, 0, 0, 0 },
79+
{ 1, 1, 0, 1 },
80+
{ 0, 1, 0, 0 },
81+
{ 1, 1, 1, 1 } };
82+
83+
N = maze.length;
84+
rat.solveMaze(maze);
85+
}
86+
}

0 commit comments

Comments
 (0)