The Rat in a Maze problem is a popular algorithmic problem in which a rat needs to find a path through a maze from a starting point to a destination. The maze is represented by a 2D grid, where each cell can either be open or blocked. The goal is to determine if there exists a path for the rat to reach the destination and, if so, we need to find such a path.
In this article, we will learn how to solve the Rat in a Maze problem using the C++ programming language with a backtracking approach.
Example
Input:

Output:
DRDDRR
Explanation:

Rat in a Maze Using Backtracking in C++
To solve the Rat in a Maze problem, we can use backtracking which is a general algorithmic technique that considers all possible paths and recurses to explore each one. If a path doesn’t lead to a solution, the algorithm backtracks and tries a different path.
Approach:
- Begin at the top-left corner of the maze.
- From the current cell, explore moving in four possible directions (up, down, left, right).
- Ensure that each move is valid (i.e., within maze boundaries and on an open cell).
- Mark the current cell as part of the path if it is valid.
- Recursively attempt to solve the maze from the next cell.
- If the move does not lead to a solution, backtrack by unmarking the current cell and trying a different path.
- If the destination is reached, the path is found.
C++ Program to Solve Rat in a Maze Using Backtracking
The below program demonstrates how we can solve rat in a maze using backtracking in C++.
//C++ program to solve rat in a maze problem using backtracking
#include <iostream>
#include <vector>
using namespace std;
// Initialize a string direction which represents all the
// directions.
string direction = "DLRU";
// Arrays to represent change in rows and columns
int dr[4] = { 1, 0, 0, -1 };
int dc[4] = { 0, -1, 1, 0 };
// Function to check if cell(row, col) is inside the maze
// and unblocked
bool isValid(int row, int col, int n, vector<vector<int> >& maze){
return row >= 0 && col >= 0 && row < n && col < n
&& maze[row][col];
}
// Function to get all valid paths
void findPath(int row, int col, vector<vector<int> >& maze,
int n, vector<string>& ans,
string& currentPath){
// If we reach the bottom right cell of the matrix, add
// the current path to ans and return
if (row == n - 1 && col == n - 1) {
ans.push_back(currentPath);
return;
}
// Mark the current cell as blocked
maze[row][col] = 0;
for (int i = 0; i < 4; i++) {
// Find the next row based on the current row (row)
// and the dr[] array
int nextrow = row + dr[i];
// Find the next column based on the current column
// (col) and the dc[] array
int nextcol = col + dc[i];
// Check if the next cell is valid or not
if (isValid(nextrow, nextcol, n, maze)) {
currentPath += direction[i];
// Recursively call the FindPath function for
// the next cell
findPath(nextrow, nextcol, maze, n, ans,
currentPath);
// Remove the last direction when backtracking
currentPath.pop_back();
}
}
// Mark the current cell as unblocked
maze[row][col] = 1;
}
int main(){
vector<vector<int> > maze = { { 1, 0, 0, 0 },
{ 1, 1, 0, 1 },
{ 1, 1, 0, 0 },
{ 0, 1, 1, 1 } };
int n = maze.size();
// vector to store all the valid paths
vector<string> result;
// Store current path
string currentPath = "";
if (maze[0][0] != 0 && maze[n - 1][n - 1] != 0) {
// Function call to get all valid paths
findPath(0, 0, maze, n, result, currentPath);
}
if (result.size() == 0)
cout << -1;
else
for (int i = 0; i < result.size(); i++)
cout << result[i] << " ";
cout << endl;
return 0;
}
Output
DDRDRR DRDDRR
Time Complexity: O(3^(m*n)), because on every cell we have to try 3 different directions , as we will not check for the cell from which we have visited in the last move.
Auxiliary Space: O(m*n), Maximum Depth of the recursion tree(auxiliary space).