Open In App
Related Articles

Rat in a Maze

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking.

Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach the destination at (N – 1, N – 1). Find all possible paths that the rat can take to reach from source to destination. The directions in which the rat can move are ‘U'(up)‘D'(down)‘L’ (left)‘R’ (right). Value 0 at a cell in the matrix represents that it is blocked and rat cannot move to it while value 1 at a cell in the matrix represents that rat can be travel through it. Return the list of paths in lexicographically increasing order.
Note: In a path, no cell can be visited more than one time. If the source cell is 0, the rat cannot move to any other cell.

Example:

Input:

Output: DRDDRR
Explanation:

Rat in a Maze using Backtracking:

We use a backtracking algorithm to explore all possible paths. While exploring the paths we keep track of the directions we have moved so far and when we reach to the bottom right cell, we record the path in a vector of strings.

Step-by-step approach:

  • Create isValid() function to check if a cell at position (r, c) is inside the maze and unblocked.
  • Create findPath() to get all valid paths:
    • Base case: If the current position is the bottom-right cell, add the current path to the result and return.
    • Mark the current cell as blocked.
    • Iterate through all possible directions.
      • Calculate the next position based on the current direction.
      • If the next position is valid (i.e, if isValid() return true), append the direction to the current path and recursively call the findPath() function for the next cell.
      • Backtrack by removing the last direction from the current path.
  • Mark the current cell as unblocked before returning.

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>
using namespace std;
 
string direction = "DLRU";
int dr[4] = {1, 0, 0, -1};
int dc[4] = {0, -1, 1, 0};
 
bool isValid(int r, int c, int n, vector<vector<int>>& maze)
{
    return r >= 0 && c >= 0 && r < n && c < n && maze[r];
}
 
void findPath(int r, int c, vector<vector<int>>& maze, int n, vector<string>& ans, string& currentPath)
{
    if (r == n - 1 && c == n - 1)
    {
        ans.push_back(currentPath);
        return;
    }
 
    maze[r] = 0;
 
    for (int i = 0; i < 4; i++)
    {
        int nextr = r + dr[i];
        int nextc = c + dc[i];
        if (isValid(nextr, nextc, n, maze))
        {
            currentPath += direction[i];
            findPath(nextr, nextc, maze, n, ans, currentPath);
            currentPath.pop_back();
        }
    }
    maze[r] = 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<string> result;
    string currentPath = "";
 
    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;
}

                    

Java

import java.util.ArrayList;
import java.util.List;
 
public class Main {
    static String direction = "DLRU";
    static int[] dr = {1, 0, 0, -1};
    static int[] dc = {0, -1, 1, 0};
 
    static boolean isValid(int r, int c, int n, List<List<Integer>> maze) {
        return r >= 0 && c >= 0 && r < n && c < n && maze.get(r).get(c) == 1;
    }
 
    static void findPath(int r, int c, List<List<Integer>> maze, int n, List<String> ans, StringBuilder currentPath) {
        if (r == n - 1 && c == n - 1) {
            ans.add(currentPath.toString());
            return;
        }
 
        maze.get(r).set(c, 0);
 
        for (int i = 0; i < 4; i++) {
            int nextr = r + dr[i];
            int nextc = c + dc[i];
            if (isValid(nextr, nextc, n, maze)) {
                currentPath.append(direction.charAt(i));
                findPath(nextr, nextc, maze, n, ans, currentPath);
                currentPath.deleteCharAt(currentPath.length() - 1);
            }
        }
        maze.get(r).set(c, 1);
    }
 
    public static void main(String[] args) {
        List<List<Integer>> maze = new ArrayList<>();
        maze.add(new ArrayList<>(List.of(1, 0, 0, 0)));
        maze.add(new ArrayList<>(List.of(1, 1, 0, 1)));
        maze.add(new ArrayList<>(List.of(1, 1, 0, 0)));
        maze.add(new ArrayList<>(List.of(0, 1, 1, 1)));
 
        int n = maze.size();
        List<String> result = new ArrayList<>();
        StringBuilder currentPath = new StringBuilder();
 
        findPath(0, 0, maze, n, result, currentPath);
 
        if (result.isEmpty())
            System.out.println(-1);
        else
            result.forEach(path -> System.out.print(path + " "));
        System.out.println();
    }
}

                    

Python3

direction = "DLRU"
dr = [1, 0, 0, -1]
dc = [0, -1, 1, 0]
 
def is_valid(r, c, n, maze):
    return 0 <= r < n and 0 <= c < n and maze[r] == 1
 
def find_path(r, c, maze, n, ans, current_path):
    if r == n - 1 and c == n - 1:
        ans.append(current_path[:])
        return
 
    maze[r] = 0
 
    for i in range(4):
        nextr = r + dr[i]
        nextc = c + dc[i]
        if is_valid(nextr, nextc, n, maze):
            current_path.append(direction[i])
            find_path(nextr, nextc, maze, n, ans, current_path)
            current_path.pop()
 
    maze[r] = 1
 
if __name__ == "__main__":
    maze = [
        [1, 0, 0, 0],
        [1, 1, 0, 1],
        [1, 1, 0, 0],
        [0, 1, 1, 1]
    ]
 
    n = len(maze)
    result = []
    current_path = []
 
    find_path(0, 0, maze, n, result, current_path)
 
    if not result:
        print(-1)
    else:
        for path in result:
            print("".join(path), end=" ")
        print()

                    

C#

using System;
using System.Collections.Generic;
 
class Program
{
    // Initialize a string direction which represents all the directions.
    static string direction = "DLRU";
 
    // Arrays to represent change in rows and columns
    static int[] dr = { 1, 0, 0, -1 };
    static int[] dc = { 0, -1, 1, 0 };
 
    // Function to check if cell(r, c) is inside the maze and unblocked
    static bool IsValid(int r, int c, int n, int[,] maze)
    {
        return r >= 0 && c >= 0 && r < n && c < n && maze[r, c] == 1;
    }
 
    // Function to get all valid paths
    static void FindPath(int r, int c, int[,] maze, int n, List<string> ans, ref string currentPath)
    {
        // If we reach the bottom right cell of the matrix, add the current path to ans and return
        if (r == n - 1 && c == n - 1)
        {
            ans.Add(currentPath);
            return;
        }
 
        // Mark the current cell as blocked
        maze[r, c] = 0;
 
        for (int i = 0; i < 4; i++)
        {
            // Find the next row based on the current row (r) and the dr[] array
            int nextR = r + dr[i];
            // Find the next column based on the current column (c) and the dc[] array
            int nextC = c + dc[i];
 
            // Check if the next cell is valid or not
            if (IsValid(nextR, nextC, n, maze))
            {
                currentPath += direction[i];
                // Recursively call the FindPath function for the next cell
                FindPath(nextR, nextC, maze, n, ans, ref currentPath);
                currentPath = currentPath.Remove(currentPath.Length - 1); // Remove the last direction when backtracking
            }
        }
 
        // Mark the current cell as unblocked
        maze[r, c] = 1;
    }
 
    static void Main()
    {
        int n = 4;
 
        int[,] maze = {
            {1, 0, 0, 0},
            {1, 1, 0, 1},
            {1, 1, 0, 0},
            {0, 1, 1, 1}
        };
 
        // List to store all the valid paths
        List<string> result = new List<string>();
 
        // Store current Path
        string currentPath = "";
 
        // Function call to get all valid paths
        FindPath(0, 0, maze, n, result, ref currentPath);
 
        if (result.Count == 0)
        {
            Console.WriteLine(-1);
        }
        else
        {
            foreach (var path in result)
            {
                Console.Write(path + " ");
            }
            Console.WriteLine();
        }
    }
}

                    

Javascript

let direction = "DLRU";
let dr = [1, 0, 0, -1];
let dc = [0, -1, 1, 0];
 
function isValid(r, c, n, maze) {
    return r >= 0 && c >= 0 && r < n && c < n && maze[r] === 1;
}
 
function findPath(r, c, maze, n, ans, currentPath) {
    if (r === n - 1 && c === n - 1) {
        ans.push(currentPath.slice());
        return;
    }
 
    maze[r] = 0;
 
    for (let i = 0; i < 4; i++) {
        let nextr = r + dr[i];
        let nextc = c + dc[i];
        if (isValid(nextr, nextc, n, maze)) {
            currentPath.push(direction.charAt(i));
            findPath(nextr, nextc, maze, n, ans, currentPath);
            currentPath.pop();
        }
    }
 
    maze[r] = 1;
}
 
let maze = [
    [1, 0, 0, 0],
    [1, 1, 0, 1],
    [1, 1, 0, 0],
    [0, 1, 1, 1]
];
 
let n = maze.length;
let result = [];
let currentPath = [];
 
findPath(0, 0, maze, n, result, currentPath);
 
if (result.length === 0) {
    console.log(-1);
} else {
    result.forEach(path => console.log(path.join("") + " "));
}

                    

Output
DDRDRR DRDDRR 





Time Complexity: O(3^(m*n)), because on every cell we have to try 3 different directions.
Auxiliary Space: O(m*n), Maximum Depth of the recursion tree(auxiliary space).



Last Updated : 28 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads