Skip to content

Commit cc005cc

Browse files
Rat in Maze problem in C++.
1 parent fe9af10 commit cc005cc

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

rat_maze.cpp

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

0 commit comments

Comments
 (0)