Here's an example code in C++ to solve the Rat in a Maze problem using recursion:
#include <iostream>
#include <vector>
using namespace std;
const int N = 4; // Size of the maze
// Function to print the solution matrix
void printSolution(const vector<vector<int>>& solution) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << solution[i][j] << " ";
}
cout << endl;
}
}
// Recursive function to solve the Rat in a Maze problem
bool solveMazeUtil(const vector<vector<int>>& maze, vector<vector<int>>& solution, int x, int y) {
// Check if (x, y) is a valid cell
if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) {
// Check if we have reached the destination (bottom-right cell)
if (x == N - 1 && y == N - 1) {
solution[x][y] = 1; // Mark the destination cell as part of the solution path
return true;
}
// Mark the current cell as part of the solution path
solution[x][y] = 1;
// Move down
if (solveMazeUtil(maze, solution, x + 1, y))
return true;
// Move right
if (solveMazeUtil(maze, solution, x, y + 1))
return true;
// If none of the above movements work, backtrack
solution[x][y] = 0;
return false;
}
return false;
}
// Function to solve the Rat in a Maze problem
void solveMaze(const vector<vector<int>>& maze) {
vector<vector<int>> solution(N, vector<int>(N, 0)); // Create a solution matrix
if (solveMazeUtil(maze, solution, 0, 0)) {
cout << "Path found! Solution:" << endl;
printSolution(solution);
} else {
cout << "No path found!" << endl;
}
}
int main() {
vector<vector<int>> maze = {
{1, 0, 0, 0},
{1, 1, 0, 1},
{0, 1, 0, 0},
{1, 1, 1, 1}
};
solveMaze(maze);
return 0;
}
Output:
Path found! Solution:
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 1
Explanation:
The code uses recursion to explore all possible paths in the maze, backtracking whenever a path does not lead to the destination. The backtracking approach ensures that all possible paths are considered, and the first valid path found is returned as the solution.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|