Open In App

Count number of ways to reach destination in a Maze

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

Input: maze = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
Output: 4
Explanation: There are four possible paths as shown in below diagram.

Reach destination in a Maze

Recommended Practice

Recursion:
When considering the cell (0,0) as the starting point, there is actually 1 way to reach it, which is by not making any move at all. This understanding helps us establish the base case for our recursive solution.

By observing the recursion tree, we can notice that there is repetition in the function calls. This is a common occurrence when multiple recursive calls are made.

We can have confidence in the recursive function’s ability to provide the number of unique paths from an intermediate point to the destination.

Since we can only move downward or to the right, we pass these options to the recursive function, trusting that it will determine the answer by traversing from these points to the destination.

By summing up the number of unique ways from the downward and rightward paths, we obtain the total number of unique ways.

C++




#include <bits/stdc++.h>
using namespace std;
 
long long int MOD = 1e9 + 7;
 
// Helper function to calculate the number of unique paths
long long int
helper(long long int m, long long int n,
       vector<vector<long long int> >& obstacleGrid)
{
    // Base cases
    if (m < 0 || n < 0) {
        return 0;
    }
 
    if (obstacleGrid[m][n] == -1) {
        return 0;
    }
 
    if (m == 0 && n == 0) {
        return 1;
    }
 
    // Recursively calculate the number of unique paths by
    // considering downward and rightward movements
    return (helper(m - 1, n, obstacleGrid) % MOD
            + helper(m, n - 1, obstacleGrid) % MOD)
           % MOD;
}
 
// Function to calculate the number of unique paths with
// obstacles
long long int uniquePathsWithObstacles(
    vector<vector<long long int> >& obstacleGrid)
{
    long long int m = obstacleGrid.size();
    long long int n = obstacleGrid[0].size();
 
    return helper(m - 1, n - 1, obstacleGrid);
}
 
int main()
{
    // Example obstacle grid
    vector<vector<long long int> > grid
        = { { 0, 0, 0, 0 },
            { 0, -1, 0, 0 },
            { -1, 0, 0, 0 },
            { 0, 0, 0, 0 } };
 
    // Calculate and print the number of unique paths with
    // obstacles
    cout << uniquePathsWithObstacles(grid);
 
    return 0;
}


Java




import java.util.*;
 
public class UniquePathsObstacles {
    static long MOD = 1000000007;
 
    // Helper function to calculate the number of unique paths
    static long helper(int m, int n, int[][] obstacleGrid) {
        // Base cases
        if (m < 0 || n < 0) {
            return 0;
        }
 
        if (obstacleGrid[m][n] == -1) {
            return 0;
        }
 
        if (m == 0 && n == 0) {
            return 1;
        }
 
        // Recursively calculate the number of unique paths by
        // considering downward and rightward movements
        return (helper(m - 1, n, obstacleGrid) % MOD
                + helper(m, n - 1, obstacleGrid) % MOD)
               % MOD;
    }
 
    // Function to calculate the number of unique paths with obstacles
    static long uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
 
        return helper(m - 1, n - 1, obstacleGrid);
    }
 
    public static void main(String[] args) {
        // Example obstacle grid
        int[][] grid = { { 0, 0, 0, 0 },
                         { 0, -1, 0, 0 },
                         { -1, 0, 0, 0 },
                         { 0, 0, 0, 0 } };
 
        // Calculate and print the number of unique paths with obstacles
        System.out.println(uniquePathsWithObstacles(grid));
    }
}


Python3




MOD = 10**9 + 7
 
# Helper function to calculate the number of unique paths
def helper(m, n, obstacleGrid):
    # Base cases
    if m < 0 or n < 0:
        return 0
 
    if obstacleGrid[m][n] == -1:
        return 0
 
    if m == 0 and n == 0:
        return 1
 
    # Recursively calculate the number of unique paths by
    # considering downward and rightward movements
    return (helper(m - 1, n, obstacleGrid) % MOD
            + helper(m, n - 1, obstacleGrid) % MOD) % MOD
 
# Function to calculate the number of unique paths with obstacles
def uniquePathsWithObstacles(obstacleGrid):
    m = len(obstacleGrid)
    n = len(obstacleGrid[0])
 
    return helper(m - 1, n - 1, obstacleGrid)
 
if __name__ == "__main__":
    # Example obstacle grid
    grid = [
        [0, 0, 0, 0],
        [0, -1, 0, 0],
        [-1, 0, 0, 0],
        [0, 0, 0, 0]
    ]
 
    # Calculate and print the number of unique paths with obstacles
    print(uniquePathsWithObstacles(grid))


C#




using System;
 
class Program
{
    static long MOD = 1000000007; // Define the modulo constant
 
    // Helper function to calculate the number of unique paths
    static long Helper(int m, int n, long[][] obstacleGrid)
    {
        // Base cases
        if (m < 0 || n < 0)
            return 0;
 
        if (obstacleGrid[m][n] == -1)
            return 0;
 
        if (m == 0 && n == 0)
            return 1;
 
        // Recursively calculate the number of unique paths by
        // considering downward and rightward movements
        return (Helper(m - 1, n, obstacleGrid) % MOD
                + Helper(m, n - 1, obstacleGrid) % MOD)
               % MOD;
    }
 
    // Function to calculate the number of unique paths with obstacles
    static long UniquePathsWithObstacles(long[][] obstacleGrid)
    {
        int m = obstacleGrid.Length;
        int n = obstacleGrid[0].Length;
 
        return Helper(m - 1, n - 1, obstacleGrid);
    }
 
    static void Main()
    {
        // Example obstacle grid
        long[][] grid =
        {
            new long[] {0, 0, 0, 0},
            new long[] {0, -1, 0, 0},
            new long[] {-1, 0, 0, 0},
            new long[] {0, 0, 0, 0}
        };
 
        // Calculate and print the number of unique paths with obstacles
        Console.WriteLine(UniquePathsWithObstacles(grid));
    }
}


Javascript




// JavaScript Program for the above approach
const MOD = 1000000007;
 
// Helper function to calculate the number of unique paths
function helper(m, n, obstacleGrid) {
    // Base cases
    if (m < 0 || n < 0) {
        return 0;
    }
 
    if (obstacleGrid[m][n] === -1) {
        return 0;
    }
 
    if (m === 0 && n === 0) {
        return 1;
    }
 
    // Recursively calculate the number of unique paths by considering downward and rightward movements
    return (helper(m - 1, n, obstacleGrid) % MOD + helper(m, n - 1, obstacleGrid) % MOD) % MOD;
}
 
// Function to calculate the number of unique paths with obstacles
function uniquePathsWithObstacles(obstacleGrid) {
    const m = obstacleGrid.length;
    const n = obstacleGrid[0].length;
 
    return helper(m - 1, n - 1, obstacleGrid);
}
 
// Example usage
const grid = [
    [0, 0, 0, 0],
    [0, -1, 0, 0],
    [-1, 0, 0, 0],
    [0, 0, 0, 0],
];
 
// Calculate and print the number of unique paths with obstacles
console.log(uniquePathsWithObstacles(grid));
// This code is contributed by Kanchan Agarwal


Output

4

Time Complexity:O(2 n * m)

Space Complexity:O(n*m)

Memoization:

We can cache the overlapping subproblems to make it a efficient solution

C++




#include <bits/stdc++.h>
using namespace std;
 
long long int MOD = 1e9 + 7;
 
// Helper function to calculate the number of unique paths
long long int
helper(long long int m, long long int n,
       vector<vector<long long int> >& dp,
       vector<vector<long long int> >& obstacleGrid)
{
    // Base case: If out of bounds or obstacle, return 0
    if (m < 0 || n < 0 || obstacleGrid[m][n] == -1) {
        return 0;
    }
 
    // Base case: If at the destination, return 1
    if (m == 0 && n == 0) {
        return 1;
    }
 
    // If already calculated, return the stored value
    if (dp[m][n] != -1) {
        return dp[m][n];
    }
 
    // Calculate the number of unique paths by moving down
    // and right
    dp[m][n] = (helper(m - 1, n, dp, obstacleGrid) % MOD
                + helper(m, n - 1, dp, obstacleGrid) % MOD)
               % MOD;
 
    return dp[m][n];
}
 
// Function to calculate the number of unique paths with
// obstacles
long long int uniquePathsWithObstacles(
    vector<vector<long long int> >& obstacleGrid)
{
    long long int m = obstacleGrid.size();
    long long int n = obstacleGrid[0].size();
 
    // Create a 2D DP matrix to store the calculated values
    vector<vector<long long int> > dp(
        m, vector<long long int>(n, -1));
 
    // Call the helper function to calculate the number of
    // unique paths
    return helper(m - 1, n - 1, dp, obstacleGrid);
}
 
int main()
{
    // Example obstacle grid
    vector<vector<long long int> > grid
        = { { 0, 0, 0, 0 },
            { 0, -1, 0, 0 },
            { -1, 0, 0, 0 },
            { 0, 0, 0, 0 } };
 
    // Calculate the number of unique paths with obstacles
    cout << uniquePathsWithObstacles(grid);
 
    return 0;
}


Java




import java.util.Arrays;
 
public class UniquePaths {
    static long MOD = 1000000007;
 
    // Helper function to calculate the number of unique paths
    static long helper(int m, int n, long[][] dp, int[][] obstacleGrid) {
        // Base case: If out of bounds or obstacle, return 0
        if (m < 0 || n < 0 || obstacleGrid[m][n] == 1) {
            return 0;
        }
 
        // Base case: If at the destination, return 1
        if (m == 0 && n == 0) {
            return 1;
        }
 
        // If already calculated, return the stored value
        if (dp[m][n] != -1) {
            return dp[m][n];
        }
 
        // Calculate the number of unique paths by moving down and right
        dp[m][n] = (helper(m - 1, n, dp, obstacleGrid) % MOD
                + helper(m, n - 1, dp, obstacleGrid) % MOD) % MOD;
 
        return dp[m][n];
    }
 
    // Function to calculate the number of unique paths with obstacles
    static long uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
 
        // Create a 2D DP matrix to store the calculated values
        long[][] dp = new long[m][n];
        for (long[] row : dp) {
            Arrays.fill(row, -1);
        }
 
        // Call the helper function to calculate the number of unique paths
        return helper(m - 1, n - 1, dp, obstacleGrid);
    }
 
    public static void main(String[] args) {
        // Example obstacle grid
        int[][] grid = {
            {0, 0, 0, 0},
            {0, 1, 0, 0},
            {1, 0, 0, 0},
            {0, 0, 0, 0}
        };
 
        // Calculate the number of unique paths with obstacles
        System.out.println(uniquePathsWithObstacles(grid));
    }
}


Python3




MOD = 10**9 + 7
 
# Helper function to calculate the number of unique paths
def helper(m, n, dp, obstacleGrid):
    # Base case: If out of bounds or obstacle, return 0
    if m < 0 or n < 0 or obstacleGrid[m][n] == -1:
        return 0
 
    # Base case: If at the destination, return 1
    if m == 0 and n == 0:
        return 1
 
    # If already calculated, return the stored value
    if dp[m][n] != -1:
        return dp[m][n]
 
    # Calculate the number of unique paths by moving down
    # and right
    dp[m][n] = (helper(m - 1, n, dp, obstacleGrid) % MOD +
                helper(m, n - 1, dp, obstacleGrid) % MOD) % MOD
 
    return dp[m][n]
 
# Function to calculate the number of unique paths with obstacles
def uniquePathsWithObstacles(obstacleGrid):
    m = len(obstacleGrid)
    n = len(obstacleGrid[0])
 
    # Create a 2D DP matrix to store the calculated values
    dp = [[-1] * n for _ in range(m)]
 
    # Call the helper function to calculate the number of
    # unique paths
    return helper(m - 1, n - 1, dp, obstacleGrid)
 
if __name__ == "__main__":
    # Example obstacle grid
    grid = [
        [0, 0, 0, 0],
        [0, -1, 0, 0],
        [-1, 0, 0, 0],
        [0, 0, 0, 0]
    ]
 
    # Calculate the number of unique paths with obstacles
    print(uniquePathsWithObstacles(grid))


C#




using System;
using System.Collections.Generic;
 
class Program {
    const long MOD = 1000000007;
 
    // Helper function to calculate the number of unique
    // paths
    static long Helper(int m, int n, long[][] dp,
                       int[][] obstacleGrid)
    {
        // Base case: If out of bounds or obstacle, return 0
        if (m < 0 || n < 0 || obstacleGrid[m][n] == -1) {
            return 0;
        }
 
        // Base case: If at the destination, return 1
        if (m == 0 && n == 0) {
            return 1;
        }
 
        // If already calculated, return the stored value
        if (dp[m][n] != -1) {
            return dp[m][n];
        }
 
        // Calculate the number of unique paths by moving
        // down and right
        dp[m][n]
            = (Helper(m - 1, n, dp, obstacleGrid) % MOD
               + Helper(m, n - 1, dp, obstacleGrid) % MOD)
              % MOD;
 
        return dp[m][n];
    }
 
    // Function to calculate the number of unique paths with
    // obstacles
    static long
    UniquePathsWithObstacles(int[][] obstacleGrid)
    {
        int m = obstacleGrid.Length;
        int n = obstacleGrid[0].Length;
 
        // Create a 2D DP matrix to store the calculated
        // values
        long[][] dp = new long[m][];
        for (int i = 0; i < m; i++) {
            dp[i] = new long[n];
            for (int j = 0; j < n; j++) {
                dp[i][j] = -1;
            }
        }
 
        // Call the helper function to calculate the number
        // of unique paths
        return Helper(m - 1, n - 1, dp, obstacleGrid);
    }
 
    static void Main()
    {
        // Example obstacle grid
        int[][] grid = { new int[] { 0, 0, 0, 0 },
                         new int[] { 0, -1, 0, 0 },
                         new int[] { -1, 0, 0, 0 },
                         new int[] { 0, 0, 0, 0 } };
 
        // Calculate the number of unique paths with
        // obstacles
        Console.WriteLine(UniquePathsWithObstacles(grid));
    }
}


Javascript




function helper(m, n, dp, obstacleGrid) {
    // Base case: If out of bounds or obstacle
    if (m < 0 || n < 0 || obstacleGrid[m][n] === 1) {
        return 0;
    }
    // Base case: If at the destination
    // return 1
    if (m === 0 && n === 0) {
        return 1;
    }
    // If already calculated
    // return the stored value
    if (dp[m][n] !== -1) {
        return dp[m][n];
    }
    // Calculate the number of unique paths by
    // moving down and right
    dp[m][n] = (helper(m - 1, n, dp, obstacleGrid) % MOD
                + helper(m, n - 1, dp, obstacleGrid) % MOD) % MOD;
 
    return dp[m][n];
}
// Function to calculate the number of
// unique paths with obstacles
function GFG(obstacleGrid) {
    const m = obstacleGrid.length;
    const n = obstacleGrid[0].length;
    // Create a 2D DP matrix to store the calculated values
    const dp = new Array(m);
    for (let i = 0; i < m; i++) {
        dp[i] = new Array(n).fill(-1);
    }
    // Call the helper function to calculate the number of the unique paths
    return helper(m - 1, n - 1, dp, obstacleGrid);
}
// Example obstacle grid
const grid = [
    [0, 0, 0, 0],
    [0, 1, 0, 0],
    [1, 0, 0, 0],
    [0, 0, 0, 0]
];
// Calculate the number of the unique paths with obstacles
const MOD = 1000000007;
console.log(GFG(grid));


Output

4

Time Complexity:O(n*m) 

Space Complexity:O(n*m)

Tabulation:

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:

C++




#include <iostream>
#include <vector>
using namespace std;
 
int FindWays(int n, int m, vector<vector<int>>& blockedCell) {
    int mod = 1000000007;
    vector<vector<int>> matrix(n + 1, vector<int>(m + 1, 0));
 
    for (int i = 0; i < blockedCell.size(); 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[1][j] = 1;
    }
 
    for (int i = 2; i <= n; i++) {
        for (int j = 2; 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];
    }
}
 
int main() {
    int n = 3, m = 3;
    vector<vector<int>> blocked_cells = { { 1, 2 }, { 3, 2 } };
    cout << FindWays(n, m, blocked_cells) << endl;
    return 0;
}


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


Python3




def find_ways(n, m, blocked_cells):
    mod = 1000000007
    matrix = [[0] * (m + 1) for _ in range(n + 1)]
 
    # Mark blocked cells with -1
    for cell in blocked_cells:
        matrix[cell[0]][cell[1]] = -1
 
    # Initialize the first column (j=1) with 1 if the cell is not blocked
    for i in range(n + 1):
        if matrix[i][1] != -1:
            matrix[i][1] = 1
 
    # Initialize the first row (i=1) with 1 if the cell is not blocked
    for j in range(m + 1):
        if matrix[1][j] != -1:
            matrix[1][j] = 1
 
    # Fill the matrix with the number of ways to reach each cell
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if matrix[i][j] == -1:
                continue
            if matrix[i - 1][j] != -1 and matrix[i][j - 1] != -1:
                # If both the cell above and the cell to the left are not blocked, add the ways to reach them
                matrix[i][j] = (matrix[i - 1][j] + matrix[i][j - 1]) % mod
            elif matrix[i - 1][j] != -1:
                # If only the cell above is not blocked, copy its value
                matrix[i][j] = matrix[i - 1][j]
            elif matrix[i][j - 1] != -1:
                # If only the cell to the left is not blocked, copy its value
                matrix[i][j] = matrix[i][j - 1]
            else:
                # If both are blocked, mark the current cell as blocked
                matrix[i][j] = -1
 
    # Check if the destination cell is blocked, return 0 if blocked, otherwise return the number of ways
    if matrix[n][m] < 0:
        return 0
    else:
        return matrix[n][m]
 
if __name__ == "__main__":
    n = 3
    m = 3
    blocked_cells = [[1, 2], [3, 2]]
    print(find_ways(n, m, blocked_cells))


C#




using System;
using System.Collections.Generic;
 
class Program {
    // Function to find the number of ways to reach the
    // bottom-right cell considering blocked cells in an n x
    // m matrix
    static int FindWays(int n, int m,
                        List<List<int> > blockedCell)
    {
        int mod = 1000000007;
        int[, ] matrix = new int[n + 1, m + 1];
 
        // Marking blocked cells in the matrix
        foreach(var cell in blockedCell)
        {
            matrix[cell[0], cell[1]] = -1;
        }
 
        // Initializing the leftmost column
        for (int i = 0; i <= n; i++) {
            if (matrix[i, 1] != -1)
                matrix[i, 1] = 1;
        }
 
        // Initializing the topmost row
        for (int j = 0; j <= m; j++) {
            if (matrix[1, j] != -1)
                matrix[1, j] = 1;
        }
 
        // Filling the matrix based on the blocked cells
        for (int i = 2; i <= n; i++) {
            for (int j = 2; j <= m; j++) {
                if (matrix[i, j] == -1) {
                    continue;
                }
 
                // Updating the number of ways based on the
                // cells above and left
                if (matrix[i - 1, j] != -1
                    && matrix[i, j - 1] != -1) {
                    matrix[i, j] = (matrix[i - 1, j]
                                    + matrix[i, j - 1])
                                   % mod;
                }
                // If the cell above is not blocked
                else if (matrix[i - 1, j] != -1) {
                    matrix[i, j] = matrix[i - 1, j];
                }
                // If the cell to the left is not blocked
                else if (matrix[i, j - 1] != -1) {
                    matrix[i, j] = matrix[i, j - 1];
                }
                // If both cells above and left are blocked,
                // mark the current cell as blocked
                else {
                    matrix[i, j] = -1;
                }
            }
        }
 
        // Checking if the bottom-right cell is blocked
        if (matrix[n, m] < 0) {
            return 0;
        }
        else {
            // Returning the number of ways to reach the
            // bottom-right cell
            return matrix[n, m];
        }
    }
 
    static void Main()
    {
        int n = 3, m = 3;
        List<List<int> > blocked_cells
            = new List<List<int> >{ new List<int>{ 1, 2 },
                                    new List<int>{ 3, 2 } };
 
        // Calling the function and printing the result
        Console.WriteLine(FindWays(n, m, blocked_cells));
    }
}


Javascript




function findWays(n, m, blockedCell) {
    const mod = 1000000007;
    const matrix = new Array(n + 1).fill(0).map(() => new Array(m + 1).fill(0));
 
    // Marking blocked cells in the matrix
    blockedCell.forEach(cell => {
        matrix[cell[0]][cell[1]] = -1;
    });
 
    // Initializing the leftmost column
    for (let i = 0; i <= n; i++) {
        if (matrix[i][1] !== -1) {
            matrix[i][1] = 1;
        }
    }
 
    // Initializing the topmost row
    for (let j = 0; j <= m; j++) {
        if (matrix[1][j] !== -1) {
            matrix[1][j] = 1;
        }
    }
 
    // Filling the matrix based on the blocked cells
    for (let i = 2; i <= n; i++) {
        for (let j = 2; j <= m; j++) {
            if (matrix[i][j] === -1) {
                continue;
            }
 
            // Updating the number of ways based on the cells above and left
            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;
            }
        }
    }
 
    // Checking if the bottom-right cell is blocked
    if (matrix[n][m] < 0) {
        return 0;
    } else {
        // Returning the number of ways to reach the bottom-right cell
        return matrix[n][m];
    }
}
 
// Example usage
const n = 3, m = 3;
const blockedCells = [
    [1, 2],
    [3, 2]
];
 
// Calling the function and printing the result
console.log(findWays(n, m, blockedCells));


Output

2

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.


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>


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


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. 



Similar Reads

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
Count total ways to reach destination from source in an undirected Graph
Given an undirected graph, a source vertex ‘s’ and a destination vertex ‘d’, the task is to count the total paths from the given ‘s’ to ‘d’. Examples Input: s = 1, d = 4 Output: 2 Explanation: Below are the 2 paths from 1 to 4 1 -&gt; 3 -&gt; 4 1 -&gt; 2 -&gt; 3 -&gt; 4 Input: s = 3, d = 9 Output: 6 Explanation: Below are the 6 paths from 3 to 9 3
12 min read
Count ways to reach destination of given Graph in minimum time
Given an undirected graph with N nodes (numbered from 0 to N-1) such that any node can be reached from any other node and there are no parallel edges. Also, an integer array edges[] is given where each element is of the form {u, v, t} which represents an edge between u and v and it takes t time to move on the edge. The task is to find the number of
18 min read
Number of ways to reach at destination in shortest time
Given an integer n and a 2D integer array of edges where edges[i] = [ui, vi, timei] means that there is an edge between intersections ui and vi that takes time i to reach. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time, the task is to return the number of ways you can arrive
11 min read
Minimum number of moves required to reach the destination by the king in a chess board
Given four integers sourceX, sourceY, destinationX and destinationY which represent the source and destination coordinates on a chessboard. The task is to find the minimum number of moves required by the king to reach from source to destination. A king can move to the square that has a common side or a common vertex with the square the king is curr
7 min read
Check if it is possible to reach destination in even number of steps in an Infinite Matrix
Given a source and destination in a matrix[][] of infinite rows and columns, the task is to find whether it is possible to reach the destination from the source in an even number of steps. Also, you can only move up, down, left, and right. Examples: Input: Source = {2, 1}, Destination = {1, 4}Output: Yes Input: Source = {2, 2}, Destination = {1, 4}
5 min read
Number of decisions to reach destination
Given a grid which consists of 4 types of characters : ‘B’ ‘.’ ‘S’ and ‘D’. We need to reach D starting from S, at each step we can go to neighboring cells i.e. up, down, left and right. Cells having character ‘B’ are blocked i.e. at any step we can’t move to cell having ‘B’. Given grid has dots in such a way that there is only one way to reach any
11 min read
Minimum possible modifications in the matrix to reach destination
Given a matrix of size N x M consisting of integers 1, 2, 3 and 4. Each value represents the possible movement from that cell: 1 -&gt; move left 2 -&gt; move right 3 -&gt; move up 4 -&gt; move down. The task is to find the minimum possible changes required in the matrix such that there exists a path from (0, 0) to (N-1, M-1). Examples: Input : mat[
28 min read
Minimize steps defined by a string required to reach the destination from a given source
Given a string str and four integers X1, Y1, X2 and Y2, where (X1, Y1) denotes the source coordinates and (X2, Y2) denotes the coordinates of the destination. Given a string str, the task is to find the minimum number of steps of the following four types required to reach destination from the source: If str[i] = 'E': Convert (X1, Y1) to (X1 + 1, Y1
11 min read
Check if a Rook can reach the given destination in a single move
Given integers current_row and current_col, representing the current position of a Rook on an 8 × 8 chessboard and two more integers destination_row and destination_col which represents the position to be reached by a Rook. The task is to check if it is possible or not for a Rook to reach the given destination in a single move from its current posi
4 min read