Backtracking Set 2 Rat in A Maze GeeksforGeeks
Backtracking Set 2 Rat in A Maze GeeksforGeeks
Login/Register
{1, 0, 0, 0}
{1, 1, 0, 1}
{0, 1, 0, 0}
{1, 1, 1, 1}
{1, 0, 0, 0}
{1, 1, 0, 0}
{0, 1, 0, 0}
{0, 1, 1, 1}
All enteries in solution path are marked as 1.
Naive Algorithm
The Naive Algorithm is to generate all paths from source to destination
and one by one check if the
generated path satisfies the constraints.
Backtrackng Algorithm
If destination is reached
print the solution matrix
Else
a) Mark current cell in solution matrix as 1.
b) Move forward in horizontal direction and recursively check if this
move leads to a solution.
c) If the move chosen in the above step doesn't lead to a solution
then move down and check if this move leads to a solution.
d) If none of the above solutions work then unmark this cell as 0
(BACKTRACK) and return false.
C/C++
/* C/C++ program to solve Rat in a Maze problem using
backtracking */
#include<stdio.h>
// Maze size
#define N 4
return false;
}
printSolution(sol);
return true;
}
/* A recursive utility function to solve Maze problem */
bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N])
{
// if (x,y is goal) return true
if(x == N‐1 && y == N‐1)
{
{
sol[x][y] = 1;
return true;
}
return false;
}
solveMaze(maze);
return 0;
}
Run on IDE
Java
/* Java program to solve Rat in a Maze problem using
backtracking */
return false;
}
}
Run on IDE
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Please write comments if you find anything incorrect, or you want to share more inf
ormation about the
topic discussed above.
Free Google
Courses Learn
New Digital Skills
Get trained with Google official
courses. Sign up and start your
learning today
learndigital.withgoogle.com
GATE CS Corner Company Wise Coding Practice
Backtracking
Recommended Posts:
Mark as DONE
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share
the link here.
Load Comments
Share this post!