The Wayback Machine - https://web.archive.org/web/20240923092457/https://www.geeksforgeeks.org/rat-in-a-maze/
Open In App

Rat in a Maze

Last Updated : 18 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 (row, col) 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;

// 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;
}
Java
import java.util.ArrayList;
import java.util.List;

public class MazePaths {

    // 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(row, col) is inside the
    // maze and unblocked
    static boolean isValid(int row, int col, int n,
                           int[][] maze)
    {
        return row >= 0 && col >= 0 && row < n && col < n
            && maze[row][col] == 1;
    }

    // Function to get all valid paths
    static void findPath(int row, int col, int[][] maze,
                         int n, ArrayList<String> ans,
                         StringBuilder 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.add(currentPath.toString());
            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.append(direction.charAt(i));
                // Recursively call the FindPath function
                // for the next cell
                findPath(nextrow, nextcol, maze, n, ans,
                         currentPath);
                // Remove the last direction when
                // backtracking
                currentPath.deleteCharAt(
                    currentPath.length() - 1);
            }
        }
        // Mark the current cell as unblocked
        maze[row][col] = 1;
    }

    public static void main(String[] args)
    {
        int[][] maze = { { 1, 0, 0, 0 },
                         { 1, 1, 0, 1 },
                         { 1, 1, 0, 0 },
                         { 0, 1, 1, 1 } };

        int n = maze.length;
        // List to store all the valid paths
        ArrayList<String> result = new ArrayList<>();
        // Store current path
        StringBuilder currentPath = new StringBuilder();

        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)
            System.out.println(-1);
        else
            for (String path : result)
                System.out.print(path + " ");
        System.out.println();
    }
}
Python
# Initialize a string direction which represents all the directions.
direction = "DLRU"

# Arrays to represent change in rows and columns
dr = [1, 0, 0, -1]
dc = [0, -1, 1, 0]

# Function to check if cell(row, col) is inside the maze
# and unblocked


def is_valid(row, col, n, maze):
    return 0 <= row < n and 0 <= col < n and maze[row][col] == 1

# Function to get all valid paths


def find_path(row, col, maze, n, ans, current_path):
    # If we reach the bottom right cell of the matrix, add
    # the current path to ans and return
    if row == n - 1 and col == n - 1:
        ans.append(current_path)
        return
    # Mark the current cell as blocked
    maze[row][col] = 0

    for i in range(4):
        # Find the next row based on the current row (row)
        # and the dr[] array
        next_row = row + dr[i]
        # Find the next column based on the current column
        # (col) and the dc[] array
        next_col = col + dc[i]

        # Check if the next cell is valid or not
        if is_valid(next_row, next_col, n, maze):
            current_path += direction[i]
            # Recursively call the find_path function for
            # the next cell
            find_path(next_row, next_col, maze, n, ans, current_path)
            # Remove the last direction when backtracking
            current_path = current_path[:-1]

    # Mark the current cell as unblocked
    maze[row][col] = 1


# Driver code
maze = [
    [1, 0, 0, 0],
    [1, 1, 0, 1],
    [1, 1, 0, 0],
    [0, 1, 1, 1]
]

n = len(maze)
# List to store all the valid paths
result = []
# Store current path
current_path = ""

if maze[0][0] != 0 and maze[n - 1][n - 1] != 0:
    # Function call to get all valid paths
    find_path(0, 0, maze, n, result, current_path)

if not result:
    print(-1)
else:
    print(" ".join(result))
C#
using System;
using System.Collections.Generic;

public class Program
{
    // Initialize an array to represent the change in rows and columns
    static int[] dr = { 1, 0, 0, -1 };
    static int[] dc = { 0, -1, 1, 0 };
    static string direction = "DLRU";

    // Function to check if cell (row, col) is inside the maze and unblocked
    static bool IsValid(int row, int col, int n, int[,] maze)
    {
        return row >= 0 && col >= 0 && row < n && col < n && maze[row, col] == 1;
    }

    // Function to get all valid paths
    static void FindPath(int row, int col, 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 (row == n - 1 && col == n - 1)
        {
            ans.Add(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, ref currentPath);
                // Remove the last direction when backtracking
                currentPath = currentPath.Remove(currentPath.Length - 1);
            }
        }

        // Mark the current cell as unblocked
        maze[row, col] = 1;
    }

    public static void Main()
    {
        int[,] maze = {
            { 1, 0, 0, 0 },
            { 1, 1, 0, 1 },
            { 1, 1, 0, 0 },
            { 0, 1, 1, 1 }
        };

        int n = maze.GetLength(0);
        // List to store all the valid paths
        List<string> result = new List<string>();
        // 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, ref currentPath);
        }

        if (result.Count == 0)
            Console.WriteLine(-1);
        else
            foreach (string path in result)
                Console.Write(path + " ");
        Console.WriteLine();
    }
}
JavaScript
// Initialize a string direction which represents all the directions.
const direction = "DLRU";

// Arrays to represent change in rows and columns
const dr = [1, 0, 0, -1];
const dc = [0, -1, 1, 0];

// Function to check if cell(row, col) is inside the maze
// and unblocked
function isValid(row, col, n, maze) {
    return row >= 0 && col >= 0 && row < n && col < n
        && maze[row][col] === 1;
}

// Function to get all valid paths
function findPath(row, col, maze, n, ans, 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(currentPath);
        return;
    }
    // Mark the current cell as blocked
    maze[row][col] = 0;

    for (let i = 0; i < 4; i++) {
        // Find the next row based on the current row (row)
        // and the dr[] array
        const nextrow = row + dr[i];
        // Find the next column based on the current column
        // (col) and the dc[] array
        const 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 = currentPath.slice(0, -1);
        }
    }
    // Mark the current cell as unblocked
    maze[row][col] = 1;
}

// Driver code
const maze = [
    [1, 0, 0, 0],
    [1, 1, 0, 1],
    [1, 1, 0, 0],
    [0, 1, 1, 1]
];

const n = maze.length;
// Array to store all the valid paths
const result = [];
// Store current path
let 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.length === 0)
    console.log(-1);
else
    console.log(result.join(" "));

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).



Previous Article
Next Article

Similar Reads

Rat in a Maze | Backtracking using Stack
Prerequisites - Recursion, Backtracking and Stack Data Structure. A Maze is given as N*M binary matrix of blocks and there is a rat initially at (0, 0) ie. maze[0][0] and the rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is a dead end and 1 means that the block can be used
15+ min read
Rat in a Maze with multiple steps or jump allowed
This is the variation of Rat in Maze A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. In the maze matrix
13 min read
Count number of ways to reach destination in a maze
Given a maze of 0 and -1 cells, the task is to find all the paths from (0, 0) to (n-1, m-1), and every path should pass through at least one cell which contains -1. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. This problem is a variation of the problem published here.Examples: Input: maze[][] = { {0, 0, 0, 0}, {0,
14 min read
Maze With N doors and 1 Key
Given an N * N binary maze where a 0 denotes that the position can be visited and a 1 denotes that the position cannot be visited without a key, the task is to find whether it is possible to visit the bottom-right cell from the top-left cell with only one key along the way. If possible then print "Yes" else print "No". Example: Input: maze[][] = {
14 min read
Geek in a Maze
Geek is in a maze of size N * M. Each cell in the maze is made of either '.' or '#'. An empty cell is represented by '.' and an obstacle is represented by '#'. The task is to find out how many different empty cells he can pass through If Geek starts at cell (R, C) and avoids the obstacles and he can move in any of the four directions but he can mov
15 min read
Random Acyclic Maze Generator with given Entry and Exit point
Given two integers N and M, the task is to generate any N * M sized maze containing only 0 (representing a wall) and 1 (representing an empty space where one can move) with the entry point as P0 and exit point P1 and there is only one path between any two movable positions. Note: P0 and P1 will be marked as 2 and 3 respectively and one can move thr
15+ min read
Shortest path in a Binary Maze
Given an MxN matrix where each element can either be 0 or 1. We need to find the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1. Example: Input: mat[ROW][COL] = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, {0, 0, 0,
15+ min read
Find paths from corner cell to middle cell in maze
Given a square maze containing positive numbers, find all paths from a corner cell (any of the extreme four corners) to the middle cell. We can move exactly n steps from a cell in 4 directions i.e. North, East, West and South where n is value of the cell, We can move to mat[i+n][j], mat[i-n][j], mat[i][j+n], and mat[i][j-n] from a cell mat[i][j] wh
15+ min read
Possibility of moving out of maze
Given n integers in a maze indicating a number of moves to be made from that position and a string which has "&gt;" and "&lt;" indicating which side to move. The starting position is the first position. Print whether it stays inside the array or moves out of the array. Example: Input : 3 2 1 1 &gt; &gt; &lt; Output: It stays inside forever Explanat
8 min read
Count paths with maximum sum from top-left to bottom-right cell (Adventure in a Maze)
Given a 2D grid maze[][] of size N * N containing numbers 1, 2 or 3 where 1: means we can go Right from that cell only, 2 means we can go Down from that cell only and 3 means we can go Right and Down to both paths from that cell. We cannot go out of the maze at any time. Find the total number of paths from cell (0, 0) to cell (N - 1, N - 1). There
14 min read
Count number of ways to reach destination in a Maze
Given a maze[][] of dimension N X M, such that maze[i][j] = -1 represents a blocked cell and maze[i][j] = 0 represents an unblocked cell. The task is to count the number of ways to reach bottom-right cell starting from top-left cell by moving right (i, j+1) and down (i+1, j) in the maze. Note: You can only pass through the unblocked cells. Examples
15+ min read
Find the largest sum of a cycle in the maze
Given a maze with N cells. Each cell may have multiple entry points but not more than one exit(i.e entry/exit points are unidirectional doors like valves).You are given an array Edge[] of N integers, where Edge[i] contains the cell number that can be reached from of cell i in one step. Edge[i] is -1 if the ith cell doesn't have an exit. The task is
9 min read
Balls rolling in the maze
Given a 2D array maze[][] of size M x N, one ball is dropped in each column. The maze is open on the top and bottom sides. Each cell in the box has a diagonal wall spanning two corners of the cell that can redirect a ball to the right or to the left. A cell that redirects the ball to the right spans the top-left corner to the bottom-right corner an
11 min read
Count number of ways to reach destination in a Maze using BFS
Given a maze with obstacles, count number of paths to reach rightmost-bottom most cell from the topmost-leftmost cell. A cell in the given maze has value -1 if it is a blockage or dead-end, else 0. From a given cell, we are allowed to move to cells (i+1, j) and (i, j+1) only. Examples: Input: mat[][] = { {1, 0, 0, 1}, {1, 1, 1, 1}, {1, 0, 1, 1}} Ou
7 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step.  Level 1Problems Solve Find a peak element which is not smaller than its neighborsSolveFind the minimum and maximum element i
3 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. Bubble Sort AlgorithmIn Bubble Sort algorithm,  traverse from left and compare adjacent elements and the
9 min read
Selection Sort Algorithm
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.  The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first e
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort work? Details of Partition Algorithm and Illustration : Illustration of QuickSort: Code impleme
14 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is a stable sorting algorithm, meaning that elements with equal values maintain their relative order in the sorted output. Insertion sort is like sorting playing cards in you
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal. Example: Input: V = 5, E = 5, edges = {{1
15+ min read
KMP Algorithm for Pattern Searching
Given two strings txt and pat of size N and M, where N &gt; M. String txt and pat represent the text and pattern respectively. The task is to print all indexes of occurrences of pattern string in the text string. Use one-based indexing while returning the indices. Examples: Input:  txt = "THIS IS A TEST TEXT", pat = "TEST"Output: Pattern found at i
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read