Backtracking - Rat in a Maze C++

 Backtracking is a powerful algorithm used in computer science to solve problems that involve finding all possible solutions to a given problem. The Rat in a Maze problem is one such problem that can be solved using backtracking. In this article, we will discuss the Rat in a Maze problem and how to solve it using backtracking in C++.

The Rat in a Maze problem is a classic problem that involves a rat trying to find its way out of a maze. The maze is represented as a 2-dimensional matrix where each cell represents a point in the maze. Some cells are blocked and cannot be traversed, while other cells are open and can be traversed. The goal of the rat is to find its way from the start cell to the end cell, moving only through open cells.

One way to solve the Rat in a Maze problem is to use backtracking. Backtracking is a technique that involves trying different solutions and undoing them when they lead to dead ends. The idea behind backtracking is to explore all possible paths until a solution is found. In the case of the Rat in a Maze problem, we can use backtracking to explore all possible paths from the start cell to the end cell, and return the first path that leads to the end cell.

The C++ code for solving the Rat in a Maze problem using backtracking is given below:

#include <iostream>
using namespace std;

const int N = 5;

// Function to check if a cell is valid
bool isValid(int x, int y, int maze[N][N]) {
    if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) {
        return true;
    }
    return false;
}

// Function to print the solution
void printSolution(int solution[N][N]) {
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            cout << solution[i][j] << " ";
        }
        cout << endl;
    }
}

// Function to solve the Rat in a Maze problem using backtracking
bool solveMaze(int maze[N][N], int x, int y, int solution[N][N]) {
    // If the current cell is the end cell, return true
    if (x == N-1 && y == N-1) {
        solution[x][y] = 1;
        return true;
    }

    // Check if the current cell is valid
    if (isValid(x, y, maze)) {
        // Mark the current cell as visited
        solution[x][y] = 1;

        // Move to the next cell in the right direction
        if (solveMaze(maze, x+1, y, solution)) {
            return true;
        }
        if (solveMaze(maze, x, y+1, solution)) {
            return true;
        }
        if (solveMaze(maze, x-1, y, solution)) {
            return true;
        }
        if (solveMaze(maze, x, y-1, solution)) {
            return true;
        }

        // If moving in the current direction leads to a dead end, undo the move
        solution[x][y] = 0;
        return false;
    }

    return false