Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Count number of ways to reach destination in a Maze

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given a maze with obstacles, count the number of paths to reach the rightmost-bottommost cell from the topmost-leftmost cell. A cell in the given maze has a value of -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: maze[R][C] =  {{0,  0, 0, 0},
                      {0, -1, 0, 0},
                      {-1, 0, 0, 0},
                      {0,  0, 0, 0}};
Output: 4
There are four possible paths as shown in
below diagram.

Recommended Practice

BRUTE APPROACH USING DP:

Intuition:

  1. We declare a 2-D matrix of size matrix[n+1][m+1]
  2. We fill the matrix with -1 where the blocked cells we given.
  3. Then we traverse through the matrix and put the sum of matrix[i-1][j] and matrix[i][j-1] if there doesn’t exist a -1.
  4. Atlast we return the matrix[n][m] as our ans

Implementation:

Java




// Java program to count number of paths in a maze
// with obstacles.
 
import java.io.*;
 
class GFG {
    public static int FindWays(int n, int m,
                               int[][] blockedCell)
    {
        int mod = 1000000007;
        int matrix[][] = new int[n + 1][m + 1];
 
        for (int i = 0; i < blockedCell.length; i++) {
            matrix[blockedCell[i][0]][blockedCell[i][1]]
                = -1;
        }
 
        for (int i = 0; i <= n; i++) {
            if (matrix[i][1] != -1)
                matrix[i][1] = 1;
        }
        for (int j = 0; j <= m; j++) {
            if (matrix[1][j] != -1)
                matrix[0][1] = 1;
        }
 
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (matrix[i][j] == -1) {
                    continue;
                }
                if (matrix[i - 1][j] != -1
                    && matrix[i][j - 1] != -1) {
                    matrix[i][j] = (matrix[i - 1][j]
                                    + matrix[i][j - 1])
                                   % mod;
                }
                else if (matrix[i - 1][j] != -1) {
                    matrix[i][j] = matrix[i - 1][j];
                }
                else if (matrix[i][j - 1] != -1) {
                    matrix[i][j] = matrix[i][j - 1];
                }
                else {
                    matrix[i][j] = -1;
                }
            }
        }
 
        if (matrix[n][m] < 0) {
            return 0;
        }
        else {
            return matrix[n][m];
        }
    }
    public static void main(String[] args)
    {
        int n = 3, m = 3;
        int[][] blocked_cells = { { 1, 2 }, { 3, 2 } };
        System.out.println(FindWays(n, m, blocked_cells));
    }
}
// This code is contributed by Raunak Singh


Output

1

Time Complexity: O(N*M)
Space Complexity: O(N*M) Since we are using a 2-D matrix

This problem is an extension of the below problem.

Backtracking | Set 2 (Rat in a Maze)

In this post, a different solution is discussed that can be used to solve the above Rat in a Maze problem also.
The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to reach (i, j) from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1. 

We can recursively compute grid[i][j] using below 
formula and finally return grid[R-1][C-1]

  // If current cell is a blockage
  if (maze[i][j] == -1)
      maze[i][j] = -1; //  Do not change

  // If we can reach maze[i][j] from maze[i-1][j]
  // then increment count.
  else if (maze[i-1][j] > 0)
      maze[i][j] = (maze[i][j] + maze[i-1][j]);

  // If we can reach maze[i][j] from maze[i][j-1]
  // then increment count.
  else if (maze[i][j-1] > 0)
      maze[i][j] = (maze[i][j] + maze[i][j-1]);

Below is the implementation of the above idea. 

C++




// C++ program to count number of paths in a maze
// with obstacles.
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
 
// Returns count of possible paths in a maze[R][C]
// from (0,0) to (R-1,C-1)
int countPaths(int maze[][C])
{
    // If the initial cell is blocked, there is no
    // way of moving anywhere
    if (maze[0][0]==-1)
        return 0;
 
    // Initializing the leftmost column
    for (int i=0; i<R; i++)
    {
        if (maze[i][0] == 0)
            maze[i][0] = 1;
 
        // If we encounter a blocked cell in leftmost
        // row, there is no way of visiting any cell
        // directly below it.
        else
            break;
    }
 
    // Similarly initialize the topmost row
    for (int i=1; i<C; i++)
    {
        if (maze[0][i] == 0)
            maze[0][i] = 1;
 
        // If we encounter a blocked cell in bottommost
        // row, there is no way of visiting any cell
        // directly below it.
        else
            break;
    }
 
    // The only difference is that if a cell is -1,
    // simply ignore it else recursively compute
    // count value maze[i][j]
    for (int i=1; i<R; i++)
    {
        for (int j=1; j<C; j++)
        {
            // If blockage is found, ignore this cell
            if (maze[i][j] == -1)
                continue;
 
            // If we can reach maze[i][j] from maze[i-1][j]
            // then increment count.
            if (maze[i-1][j] > 0)
                maze[i][j] = (maze[i][j] + maze[i-1][j]);
 
            // If we can reach maze[i][j] from maze[i][j-1]
            // then increment count.
            if (maze[i][j-1] > 0)
                maze[i][j] = (maze[i][j] + maze[i][j-1]);
        }
    }
 
    // If the final cell is blocked, output 0, otherwise
    // the answer
    return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;
}
 
// Driver code
int main()
{
    int maze[R][C] =  {{0,  0, 0, 0},
                       {0, -1, 0, 0},
                       {-1, 0, 0, 0},
                       {0,  0, 0, 0}};
    cout << countPaths(maze);
    return 0;
}


Java




// Java program to count number of paths in a maze
// with obstacles.
import java.io.*;
 
class GFG
{
    static int R = 4;
    static int C = 4;
     
    // Returns count of possible paths in
    // a maze[R][C] from (0,0) to (R-1,C-1)
    static int countPaths(int maze[][])
    {
        // If the initial cell is blocked,
        // there is no way of moving anywhere
        if (maze[0][0]==-1)
            return 0;
     
        // Initializing the leftmost column
        for (int i = 0; i < R; i++)
        {
            if (maze[i][0] == 0)
                maze[i][0] = 1;
     
            // If we encounter a blocked cell
            // in leftmost row, there is no way
            // of visiting any cell directly below it.
            else
                break;
        }
     
        // Similarly initialize the topmost row
        for (int i =1 ; i< C ; i++)
        {
            if (maze[0][i] == 0)
                maze[0][i] = 1;
     
            // If we encounter a blocked cell in
            // bottommost row, there is no way of
            // visiting any cell directly below it.
            else
                break;
        }
     
        // The only difference is that if a cell
        // is -1, simply ignore it else recursively
        // compute count value maze[i][j]
        for (int i = 1; i < R; i++)
        {
            for (int j = 1; j <C ; j++)
            {
                // If blockage is found,
                // ignore this cell
                if (maze[i][j] == -1)
                    continue;
     
                // If we can reach maze[i][j] from
                // maze[i-1][j] then increment count.
                if (maze[i - 1][j] > 0)
                    maze[i][j] = (maze[i][j] +
                                 maze[i - 1][j]);
     
                // If we can reach maze[i][j] from
                //  maze[i][j-1] then increment count.
                if (maze[i][j - 1] > 0)
                    maze[i][j] = (maze[i][j] +
                                  maze[i][j - 1]);
            }
        }
     
        // If the final cell is blocked,
        // output 0, otherwise the answer
        return (maze[R - 1][C - 1] > 0) ?
                maze[R - 1][C - 1] : 0;
    }
     
    // Driver code
 
    public static void main (String[] args)
    {
        int maze[][] = {{0, 0, 0, 0},
                       {0, -1, 0, 0},
                       {-1, 0, 0, 0},
                       {0, 0, 0, 0}};
        System.out.println (countPaths(maze));
     
    }
 
}
 
// This code is contributed by vt_m


Python3




# Python 3 program to count number of paths
# in a maze with obstacles.
 
R = 4
C = 4
 
# Returns count of possible paths in a
# maze[R][C] from (0,0) to (R-1,C-1)
def countPaths(maze):
     
    # If the initial cell is blocked,
    # there is no way of moving anywhere
    if (maze[0][0] == -1):
        return 0
 
    # Initializing the leftmost column
    for i in range(R):
        if (maze[i][0] == 0):
            maze[i][0] = 1
 
        # If we encounter a blocked cell in
        # leftmost row, there is no way of
        # visiting any cell directly below it.
        else:
            break
 
    # Similarly initialize the topmost row
    for i in range(1, C, 1):
        if (maze[0][i] == 0):
            maze[0][i] = 1
 
        # If we encounter a blocked cell in
        # bottommost row, there is no way of
        # visiting any cell directly below it.
        else:
            break
 
    # The only difference is that if a cell is -1,
    # simply ignore it else recursively compute
    # count value maze[i][j]
    for i in range(1, R, 1):
        for j in range(1, C, 1):
             
            # If blockage is found, ignore this cell
            if (maze[i][j] == -1):
                continue
 
            # If we can reach maze[i][j] from
            # maze[i-1][j] then increment count.
            if (maze[i - 1][j] > 0):
                maze[i][j] = (maze[i][j] +
                              maze[i - 1][j])
 
            # If we can reach maze[i][j] from
            # maze[i][j-1] then increment count.
            if (maze[i][j - 1] > 0):
                maze[i][j] = (maze[i][j] +
                              maze[i][j - 1])
 
    # If the final cell is blocked,
    # output 0, otherwise the answer
    if (maze[R - 1][C - 1] > 0):
        return maze[R - 1][C - 1]
    else:
        return 0
 
# Driver code
if __name__ == '__main__':
    maze = [[0, 0, 0, 0],
            [0, -1, 0, 0],
            [-1, 0, 0, 0],
            [0, 0, 0, 0 ]]
    print(countPaths(maze))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to count number of paths in a maze
// with obstacles.
using System;
 
class GFG {
     
    static int R = 4;
    static int C = 4;
     
    // Returns count of possible paths in
    // a maze[R][C] from (0,0) to (R-1,C-1)
    static int countPaths(int [,]maze)
    {
         
        // If the initial cell is blocked,
        // there is no way of moving anywhere
        if (maze[0,0]==-1)
            return 0;
     
        // Initializing the leftmost column
        for (int i = 0; i < R; i++)
        {
            if (maze[i,0] == 0)
                maze[i,0] = 1;
     
            // If we encounter a blocked cell
            // in leftmost row, there is no way
            // of visiting any cell directly below it.
            else
                break;
        }
     
        // Similarly initialize the topmost row
        for (int i =1 ; i< C ; i++)
        {
            if (maze[0,i] == 0)
                maze[0,i] = 1;
     
            // If we encounter a blocked cell in
            // bottommost row, there is no way of
            // visiting any cell directly below it.
            else
                break;
        }
     
        // The only difference is that if a cell
        // is -1, simply ignore it else recursively
        // compute count value maze[i][j]
        for (int i = 1; i < R; i++)
        {
            for (int j = 1; j <C ; j++)
            {
                // If blockage is found,
                // ignore this cell
                if (maze[i,j] == -1)
                    continue;
     
                // If we can reach maze[i][j] from
                // maze[i-1][j] then increment count.
                if (maze[i - 1,j] > 0)
                    maze[i,j] = (maze[i,j] +
                                maze[i - 1,j]);
     
                // If we can reach maze[i][j] from
                // maze[i][j-1] then increment count.
                if (maze[i,j - 1] > 0)
                    maze[i,j] = (maze[i,j] +
                                maze[i,j - 1]);
            }
        }
     
        // If the final cell is blocked,
        // output 0, otherwise the answer
        return (maze[R - 1,C - 1] > 0) ?
                maze[R - 1,C - 1] : 0;
    }
     
    // Driver code
    public static void Main ()
    {
        int [,]maze = { {0, 0, 0, 0},
                        {0, -1, 0, 0},
                        {-1, 0, 0, 0},
                        {0, 0, 0, 0}};
                         
        Console.Write (countPaths(maze));
    }
 
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// PHP program to count number
// of paths in a maze with obstacles.
 
$R = 4;
$C = 4;
 
// Returns count of possible
// paths in a maze[R][C]
// from (0,0) to (R-1,C-1)
function countPaths( $maze)
{
    global $R, $C;
     
    // If the initial cell is
    // blocked, there is no
    // way of moving anywhere
    if ($maze[0][0] == - 1)
        return 0;
 
    // Initializing the
    // leftmost column
    for ( $i = 0; $i < $R; $i++)
    {
        if ($maze[$i][0] == 0)
            $maze[$i][0] = 1;
 
        // If we encounter a blocked
        // cell in leftmost row,
        // there is no way of
        // visiting any cell
        // directly below it.
        else
            break;
    }
 
    // Similarly initialize
    // the topmost row
    for($i = 1; $i < $C; $i++)
    {
        if ($maze[0][$i] == 0)
            $maze[0][$i] = 1;
 
        // If we encounter a blocked
        // cell in bottommost row,
        // there is no way of
        // visiting any cell
        // directly below it.
        else
            break;
    }
 
    // The only difference is
    // that if a cell is -1,
    // simply ignore it else
    // recursively compute
    // count value maze[i][j]
    for($i = 1; $i < $R; $i++)
    {
        for($j = 1; $j < $C; $j++)
        {
             
            // If blockage is found,
            // ignore this cell
            if ($maze[$i][$j] == -1)
                continue;
 
            // If we can reach maze[i][j]
            // from maze[i-1][j]
            // then increment count.
            if ($maze[$i - 1][$j] > 0)
                $maze[$i][$j] = ($maze[$i][$j] +
                           $maze[$i - 1][$j]);
 
            // If we can reach maze[i][j]
            // from maze[i][j-1]
            // then increment count.
            if ($maze[$i][$j - 1] > 0)
                $maze[$i][$j] = ($maze[$i][$j] +
                             $maze[$i][$j - 1]);
        }
    }
 
    // If the final cell is
    // blocked, output 0,
    // otherwise the answer
    return ($maze[$R - 1][$C - 1] > 0) ?
            $maze[$R - 1][$C - 1] : 0;
}
 
    // Driver Code
    $maze = array(array(0, 0, 0, 0),
                  array(0, -1, 0, 0),
                  array(-1, 0, 0, 0),
                  array(0, 0, 0, 0));
    echo countPaths($maze);
 
// This code is contributed by anuj_67.
?>


Javascript




<script>
 
// JavaScript program to count number
// of paths in a maze with obstacles.
let R = 4;
let C = 4;
   
// Returns count of possible paths in
// a maze[R][C] from (0,0) to (R-1,C-1)
function countPaths(maze)
{
     
    // If the initial cell is blocked,
    // there is no way of moving anywhere
    if (maze[0][0] == -1)
        return 0;
   
    // Initializing the leftmost column
    for(let i = 0; i < R; i++)
    {
        if (maze[i][0] == 0)
            maze[i][0] = 1;
   
        // If we encounter a blocked cell
        // in leftmost row, there is no way
        // of visiting any cell directly below it.
        else
            break;
    }
   
    // Similarly initialize the topmost row
    for(let i = 1; i < C; i++)
    {
        if (maze[0][i] == 0)
            maze[0][i] = 1;
   
        // If we encounter a blocked cell in
        // bottommost row, there is no way of
        // visiting any cell directly below it.
        else
            break;
    }
   
    // The only difference is that if a cell
    // is -1, simply ignore it else recursively
    // compute count value maze[i][j]
    for(let i = 1; i < R; i++)
    {
        for(let j = 1; j < C; j++)
        {
             
            // If blockage is found,
            // ignore this cell
            if (maze[i][j] == -1)
                continue;
   
            // If we can reach maze[i][j] from
            // maze[i-1][j] then increment count.
            if (maze[i - 1][j] > 0)
                maze[i][j] = (maze[i][j] +
                              maze[i - 1][j]);
   
            // If we can reach maze[i][j] from
            //  maze[i][j-1] then increment count.
            if (maze[i][j - 1] > 0)
                maze[i][j] = (maze[i][j] +
                              maze[i][j - 1]);
        }
    }
   
    // If the final cell is blocked,
    // output 0, otherwise the answer
    return (maze[R - 1][C - 1] > 0) ?
            maze[R - 1][C - 1] : 0;
}
 
// Driver Code
let maze = [ [ 0, 0, 0, 0 ],
             [ 0, -1, 0, 0 ],
             [ -1, 0, 0, 0 ],
             [ 0, 0, 0, 0 ] ];
                
document.write(countPaths(maze));
 
// This code is contributed by code_hunt
 
</script>


Output

4

Time Complexity: O(R x C)
Auxiliary Space: O(1)

This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Last Updated : 15 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials