The Wayback Machine - https://web.archive.org/web/20250209202452/https://www.geeksforgeeks.org/unique-paths-in-a-grid-with-obstacles/
Open In App

Unique paths in a Grid with Obstacles

Last Updated : 09 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a grid[][] of size m * n, let us assume we are starting at (1, 1) and our goal is to reach (m, n). At any instance, if we are on (x, y), we can either go to (x, y + 1) or (x + 1, y). The task is to find the number of unique paths if some obstacles are added to the grid.
Note: An obstacle and space are marked as 1 and 0 respectively in the grid.

Examples:  

Input:
grid[][] = [[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]

Output: 2
Explanation: There are two ways to reach the bottom-right corner:

  • Right -> Right -> Down -> Down
  • Down -> Down -> Right -> Right

Input:
grid[][] = [[0, 1],
[0, 0]]

Output: 1
Explanation: There is only one way to reach the bottom-right corner:

  • Down -> Right

Using Recursion – O(2^(m*n)) Time and O(m+n) Space

We have discussed the problem of counting the number of unique paths in a Grid when no obstacle was present in the grid. But here the situation is quite different. While moving through the grid, we can get some obstacles that we can not jump and the way to reach the bottom right corner is blocked.

For this approach, the recursive solution will explore two main cases from each cell:

  • Move to the cell below the current position.
  • Move to the cell to the right of the current position.

Base Cases:

  • If i == r or j == c: The current position is out of bounds, so there are no paths available. Return 0.
  • If grid[i][j] == 1: The current cell is an obstacle, so it cannot be used. Return 0.
  • If i == r-1 and j == c-1: The function has reached the destination, so there is exactly one path. Return 1.

The recurrence relation will be:

  • UniquePathHelper(i, j, r, c, grid) = UniquePathHelper(i+1, j, r, c, grid) + UniquePathHelper(i, j+1, r, c, grid)
C++
// C++ code to find number of unique paths
// using Recursion
#include <bits/stdc++.h>
using namespace std;

// Helper function to find unique paths recursively
int UniquePathHelper(int i, int j, int r, int c, 
                     vector<vector<int>>& grid) {
                     
    // If out of bounds, return 0
    if(i == r || j == c) {
        return 0;
    }

    // If cell is an obstacle, return 0
    if(grid[i][j] == 1) {
        return 0;
    }
    
    // If reached the bottom-right cell, return 1
    if(i == r-1 && j == c-1) {
        return 1;
    }

    // Recur for the cell below and the cell to the right
    return UniquePathHelper(i+1, j, r, c, grid) + 
           UniquePathHelper(i, j+1, r, c, grid);
}

// Function to find unique paths with obstacles
int uniquePathsWithObstacles(vector<vector<int>>& grid) {
    int r = grid.size(), c = grid[0].size();  
    return UniquePathHelper(0, 0, r, c, grid); 
}

int main() {
  
    // Hardcoded grid with obstacles
    vector<vector<int>> grid = { { 0, 0, 0 },
                                 { 0, 1, 0 },
                                 { 0, 0, 0 } };
                             
    cout << uniquePathsWithObstacles(grid);                                                  
}
Java
// Java code to find number of unique paths
// using Recursion
import java.util.*;

class GfG {

    // Helper function to find unique paths recursively
    static int UniquePathHelper(int i, int j, int r, int c, 
                                       int[][] grid) {
        // If out of bounds, return 0
        if(i == r || j == c) {
            return 0;
        }

        // If cell is an obstacle, return 0
        if(grid[i][j] == 1) {
            return 0;
        }
        
        // If reached the bottom-right cell, return 1
        if(i == r-1 && j == c-1) {
            return 1;
        }

        // Recur for the cell below and the cell to the right
        return UniquePathHelper(i+1, j, r, c, grid) + 
               UniquePathHelper(i, j+1, r, c, grid);
    }

    // Function to find unique paths with obstacles
    static int uniquePathsWithObstacles(int[][] grid) {
        int r = grid.length, c = grid[0].length;  
        return UniquePathHelper(0, 0, r, c, grid); 
    }

    public static void main(String[] args) {
      
        int[][] grid = { { 0, 0, 0 },
                         { 0, 1, 0 },
                         { 0, 0, 0 } };
                         
        System.out.println(uniquePathsWithObstacles(grid));                                                  
    }
}
Python
# Python code to find number of unique paths
# using Recursion

# Helper function to find unique paths recursively
def UniquePathHelper(i, j, r, c, grid):
  
    # If out of bounds, return 0
    if i == r or j == c:
        return 0

    # If cell is an obstacle, return 0
    if grid[i][j] == 1:
        return 0
    
    # If reached the bottom-right cell, return 1
    if i == r-1 and j == c-1:
        return 1

    # Recur for the cell below and the cell to the right
    return UniquePathHelper(i+1, j, r, c, grid) + \
           UniquePathHelper(i, j+1, r, c, grid)

# Function to find unique paths with obstacles
def uniquePathsWithObstacles(grid):
    r, c = len(grid), len(grid[0])
    return UniquePathHelper(0, 0, r, c, grid)

if __name__ == "__main__":
  
  grid = [[0, 0, 0],
          [0, 1, 0],
          [0, 0, 0]]

  print(uniquePathsWithObstacles(grid))
C#
// C# code to find number of unique paths
// using Recursion

using System;
using System.Collections.Generic;

class GfG {

    // Helper function to find unique paths recursively
    static int UniquePathHelper(int i, int j, int r, int c, 
                                       int[,] grid) {
        // If out of bounds, return 0
        if(i == r || j == c) {
            return 0;
        }

        // If cell is an obstacle, return 0
        if(grid[i, j] == 1) {
            return 0;
        }
        
        // If reached the bottom-right cell, return 1
        if(i == r-1 && j == c-1) {
            return 1;
        }

        // Recur for the cell below and the cell to the right
        return UniquePathHelper(i+1, j, r, c, grid) + 
               UniquePathHelper(i, j+1, r, c, grid);
    }

    // Function to find unique paths with obstacles
    static int uniquePathsWithObstacles(int[,] grid) {
        int r = grid.GetLength(0), c = grid.GetLength(1);  
        return UniquePathHelper(0, 0, r, c, grid); 
    }

    static void Main() {
      
        int[,] grid = { { 0, 0, 0 },
                        { 0, 1, 0 },
                        { 0, 0, 0 } };
                         
        Console.WriteLine(uniquePathsWithObstacles(grid));                                                  
    }
}
JavaScript
// Javascript code to find number of unique paths
// using Recursion

// Helper function to find unique paths recursively
function UniquePathHelper(i, j, r, c, grid) {

    // If out of bounds, return 0
    if (i === r || j === c) {
        return 0;
    }

    // If cell is an obstacle, return 0
    if (grid[i][j] === 1) {
        return 0;
    }

    // If reached the bottom-right cell, return 1
    if (i === r - 1 && j === c - 1) {
        return 1;
    }

    // Recur for the cell below and the cell to the right
    return UniquePathHelper(i + 1, j, r, c, grid)
           + UniquePathHelper(i, j + 1, r, c, grid);
}

// Function to find unique paths with obstacles
function uniquePathsWithObstacles(grid)
{
    let r = grid.length, c = grid[0].length;
    return UniquePathHelper(0, 0, r, c, grid);
}

const grid = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ];

console.log(uniquePathsWithObstacles(grid));

Output
2

Using Top-Down DP(Memoization) – O(m*n) Time and O(m*n) Space

1. Optimal Substructure

The solution for finding unique paths from (0, 0) to (r-1, c-1) can be broken down into smaller subproblems. Specifically, to find the number of unique paths to any cell (i, j), we need the results of two smaller subproblems:

  • The number of paths to the cell below, (i+1, j).
  • The number of paths to the cell to the right, (i, j+1).

2. Overlapping Subproblems

When implementing a recursive solution to find the number of unique paths in a grid with obstacles, we observe that many subproblems are computed multiple times. For instance, when computing UniquePathHelper(i, j), where i and j represent the current cell in the grid, we might need to compute the same value for the same cell multiple times during recursion.

  • The recursive solution involves changing two parameters: the current row index i and the current column index j representing the current position in the grid. To track the results for each cell, we create a 2D array of size r x c where r is the number of rows and c is the number of columns in the grid. The value of i will range from 0 to r-1 and j will range from 0 to c-1.
  • We initialize the 2D array with -1 to indicate that no subproblems have been computed yet.
  • We check if the value at memo[i][j] is -1. If it is, we proceed to compute the result. otherwise, we return the stored result.
C++
// C++ code to find number of unique paths
// using Memoization
#include <bits/stdc++.h>
using namespace std;

// Helper function to find unique paths 
// recursively with memoization
int UniquePathHelper(int i, int j, int r, int c, 
                     vector<vector<int>>& grid, 
                     vector<vector<int>>& memo) {

    // If out of bounds, return 0
    if(i == r || j == c) {
        return 0;
    }

    // If cell is an obstacle, return 0
    if(grid[i][j] == 1) {
        return 0;
    }

    // If reached the bottom-right cell, return 1
    if(i == r-1 && j == c-1) {
        return 1;
    }

    // If value is already computed, return it
    if(memo[i][j] != -1) {
        return memo[i][j];
    }

    // Memoize the result of recursive calls
    memo[i][j] = UniquePathHelper(i+1, j, r, c, grid, memo) + 
                 UniquePathHelper(i, j+1, r, c, grid, memo);

    return memo[i][j];
}

// Function to find unique paths with obstacles
int uniquePathsWithObstacles(vector<vector<int>>& grid) {
  
    int r = grid.size(), c = grid[0].size();
    vector<vector<int>> memo(r, vector<int>(c, -1));
    return UniquePathHelper(0, 0, r, c, grid, memo);
}

int main() {

    vector<vector<int>> grid = { { 0, 0, 0 },
                                 { 0, 1, 0 },
                                 { 0, 0, 0 } };

    cout << uniquePathsWithObstacles(grid);
}
Java
// Java code to find number of unique paths
// using Memoization
import java.util.*;

class GfG {

    // Helper function to find unique paths 
    // recursively with memoization
    static int UniquePathHelper(int i, int j, int r, int c, 
                                       int[][] grid, int[][] memo) {
        // If out of bounds, return 0
        if(i == r || j == c) {
            return 0;
        }

        // If cell is an obstacle, return 0
        if(grid[i][j] == 1) {
            return 0;
        }
        
        // If reached the bottom-right cell,
          // return 1
        if(i == r-1 && j == c-1) {
            return 1;
        }

        // If value is already computed, return it
        if(memo[i][j] != -1) {
            return memo[i][j];
        }

        // Memoize the result of recursive calls
        memo[i][j] = UniquePathHelper(i+1, j, r, c, grid, memo) + 
                     UniquePathHelper(i, j+1, r, c, grid, memo);

        return memo[i][j];
    }

    // Function to find unique paths with obstacles
    static int uniquePathsWithObstacles(int[][] grid) {
      
        int r = grid.length, c = grid[0].length;
        int[][] memo = new int[r][c];
        for (int[] row : memo) Arrays.fill(row, -1);
        return UniquePathHelper(0, 0, r, c, grid, memo);
    }

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

        System.out.println(uniquePathsWithObstacles(grid));
    }
}
Python
# Python code to find number of unique paths
# using Memoization

# Helper function to find unique paths recursively 
# with memoization
def UniquePathHelper(i, j, r, c, grid, memo):
  
    # If out of bounds, return 0
    if i == r or j == c:
        return 0

    # If cell is an obstacle, return 0
    if grid[i][j] == 1:
        return 0
    
    # If reached the bottom-right cell, return 1
    if i == r-1 and j == c-1:
        return 1

    # If value is already computed, return it
    if (i, j) in memo:
        return memo[(i, j)]

    # Memoize the result of recursive calls
    memo[(i, j)] = UniquePathHelper(i+1, j, r, c, grid, memo) + \
                   UniquePathHelper(i, j+1, r, c, grid, memo)
    
    return memo[(i, j)]

# Function to find unique paths with obstacles
def uniquePathsWithObstacles(grid):
    r, c = len(grid), len(grid[0])
    memo = {}  
    return UniquePathHelper(0, 0, r, c, grid, memo)

if __name__ == "__main__":
  
  grid = [[0, 0, 0],
          [0, 1, 0],
          [0, 0, 0]]

  print(uniquePathsWithObstacles(grid))
C#
// C# code to find number of unique paths
// using Memoization
using System;
using System.Collections.Generic;

class GfG {

    // Helper function to find unique paths 
    // recursively with memoization
    static int UniquePathHelper(int i, int j,
                      int r, int c, int[,] grid, int[,] memo) {
      
        // If out of bounds, return 0
        if(i == r || j == c) {
            return 0;
        }

        // If cell is an obstacle, return 0
        if(grid[i, j] == 1) {
            return 0;
        }
        
        // If reached the bottom-right cell, return 1
        if(i == r-1 && j == c-1) {
            return 1;
        }

        // If value is already computed, return it
        if(memo[i, j] != -1) {
            return memo[i, j];
        }

        // Memoize the result of recursive calls
        memo[i, j] = UniquePathHelper(i+1, j, r, c, grid, memo) + 
                     UniquePathHelper(i, j+1, r, c, grid, memo);

        return memo[i, j];
    }

    // Function to find unique paths with obstacles
    static int uniquePathsWithObstacles(int[,] grid) {
        int r = grid.GetLength(0), c = grid.GetLength(1);
        int[,] memo = new int[r, c];
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                memo[i, j] = -1;
            }
        }
        return UniquePathHelper(0, 0, r, c, grid, memo);
    }

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

        Console.WriteLine(uniquePathsWithObstacles(grid));
    }
}
JavaScript
// Javascript code to find number of unique paths
// using Memoization

// Helper function to find unique paths 
// recursively with memoization
function UniquePathHelper(i, j, r, c, grid, memo) {

    // If out of bounds, return 0
    if (i === r || j === c) {
        return 0;
    }

    // If cell is an obstacle, return 0
    if (grid[i][j] === 1) {
        return 0;
    }
    
    // If reached the bottom-right cell, return 1
    if (i === r-1 && j === c-1) {
        return 1;
    }

    // If value is already computed, return it
    if (memo[i][j] !== -1) {
        return memo[i][j];
    }

    // Memoize the result of recursive calls
    memo[i][j] = UniquePathHelper(i+1, j, r, c, grid, memo) + 
                 UniquePathHelper(i, j+1, r, c, grid, memo);

    return memo[i][j];
}

// Function to find unique paths with obstacles
function uniquePathsWithObstacles(grid) {

    let r = grid.length, c = grid[0].length;
    let memo = Array.from({ length: r },
                   () => Array(c).fill(-1));
                   
    return UniquePathHelper(0, 0, r, c, grid, memo);
}

const grid = [[0, 0, 0],
              [0, 1, 0],
              [0, 0, 0]];

console.log(uniquePathsWithObstacles(grid));

Output
2

Using Bottom-Up DP (Tabulation) – O(m*n) Time and O(m*n) Space

In this case, the problem is to find the number of unique paths in a grid with obstacles. The state dp[i][j] will represent the number of unique paths to reach the cell (i, j).

Dynamic Programming Relation:

  • Base Case: The starting point (0, 0) is initialized to 1 if it is not an obstacle (grid[0][0] == 0).
  • For each cell (i, j): If the cell contains an obstacle (grid[i][j] == 1), then there are no paths to this cell, so dp[i][j] = 0.
  • Otherwise, if there is no obstacle, we calculate the number of paths by accumulating paths from the cell above (dp[i-1, j]) and from the left (dp[i, j-1]), i.e dp[i][j] = dp[i-1][j] + dp[i][j-1]

This means that for each cell, we check the cells directly above and to the left. If either of those cells has a valid path, we add it to the current cell.

C++
// C++ Code to find unique paths with obstacles
// using tabulation
#include <bits/stdc++.h>
using namespace std;

int uniquePathsWithObstacles(vector<vector<int>>& grid) {
    int r = grid.size(), c = grid[0].size();
    
    // Initialize DP table with zeros
    vector<vector<int>> dp(r, vector<int>(c, 0));

    // Initialize starting cell if there's no obstacle
    if(grid[0][0] == 0) {
        dp[0][0] = 1;
    }

    // Fill the DP table
    for(int i = 0; i < r; i++) {
        for(int j = 0; j < c; j++) {
          
            // If cell has an obstacle, set paths to 0
            if(grid[i][j] == 1) {
                dp[i][j] = 0;
            } else {
              
                // Accumulate paths from top cell
                if(i > 0) dp[i][j] += dp[i-1][j];
              
                // Accumulate paths from left cell
                if(j > 0) dp[i][j] += dp[i][j-1];
            }
        }
    }

    // Return paths count for the 
      // bottom-right cell
    return dp[r-1][c-1];
}

int main() {
  
    vector<vector<int>> grid = { { 0, 0, 0 },
                                 { 0, 1, 0 },
                                 { 0, 0, 0 } };

    cout << uniquePathsWithObstacles(grid);
}
Java
// Java Code to find unique paths with obstacles
// using tabulation
class GfG {

    static int uniquePathsWithObstacles(int[][] grid) {
        int r = grid.length, c = grid[0].length;
        
        // Initialize DP table with zeros
        int[][] dp = new int[r][c];

        // Initialize starting cell if 
          // there's no obstacle
        if(grid[0][0] == 0) {
            dp[0][0] = 1;
        }

        // Fill the DP table
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
              
                // If cell has an obstacle, set
                  // paths to 0
                if(grid[i][j] == 1) {
                    dp[i][j] = 0;
                } else {
                  
                    // Accumulate paths from top cell
                    if(i > 0) dp[i][j] += dp[i-1][j];
                  
                    // Accumulate paths from left cell
                    if(j > 0) dp[i][j] += dp[i][j-1];
                }
            }
        }

        // Return paths count for the 
          // bottom-right cell
        return dp[r-1][c-1];
    }

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

        System.out.println(uniquePathsWithObstacles(grid));
    }
}
Python
# Python code to find unique paths with obstacles 
# using tabulation
def uniquePathsWithObstacles(grid):
    r, c = len(grid), len(grid[0])
    
    # Initialize DP table with zeros
    dp = [[0] * c for _ in range(r)]

    # Initialize starting cell if there's 
    # no obstacle
    if grid[0][0] == 0:
        dp[0][0] = 1

    # Fill the DP table
    for i in range(r):
        for j in range(c):
          
            # If cell has an obstacle, set 
            # paths to 0
            if grid[i][j] == 1:
                dp[i][j] = 0
            else:
              
                # Accumulate paths from top cell
                if i > 0:
                    dp[i][j] += dp[i-1][j]
                    
                # Accumulate paths from left cell
                if j > 0:
                    dp[i][j] += dp[i][j-1]

    # Return paths count for the 
    # bottom-right cell
    return dp[r-1][c-1]

if __name__ == "__main__":
  
  grid = [[0, 0, 0],
          [0, 1, 0],
          [0, 0, 0]]

  print(uniquePathsWithObstacles(grid))
C#
// C# Code to find unique paths with obstacles
// using tabulation
using System;

class GfG {

    public static int uniquePathsWithObstacles(int[,] grid) {
        int r = grid.GetLength(0), c = grid.GetLength(1);
        
        // Initialize DP table with zeros
        int[,] dp = new int[r, c];

        // Initialize starting cell if there's no
          // obstacle
        if(grid[0, 0] == 0) {
            dp[0, 0] = 1;
        }

        // Fill the DP table
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
              
                // If cell has an obstacle, set 
                  // paths to 0
                if(grid[i, j] == 1) {
                  dp[i, j] = 0;
                } 
                else {
                  
                    // Accumulate paths from top cell
                    if(i > 0) dp[i, j] += dp[i-1, j];
                  
                    // Accumulate paths from left cell
                    if(j > 0) dp[i, j] += dp[i, j-1];
                }
            }
        }

        // Return paths count for the
          // bottom-right cell
        return dp[r-1, c-1];
    }

    static void Main() {
      
        int[,] grid = { { 0, 0, 0 },
                        { 0, 1, 0 },
                        { 0, 0, 0 } };
      
        Console.WriteLine(uniquePathsWithObstacles(grid));
    }
}
JavaScript
// Javascript code to find unique paths with
// obstacles using tabulation
function uniquePathsWithObstacles(grid) {

    let r = grid.length, c = grid[0].length;

    // Initialize DP table with zeros
    let dp
        = Array.from({length : r}, () => Array(c).fill(0));

    // Initialize starting cell if there's 
    // no obstacle
    if (grid[0][0] === 0) {
        dp[0][0] = 1;
    }

    // Fill the DP table
    for (let i = 0; i < r; i++) {
        for (let j = 0; j < c; j++) {

            // If cell has an obstacle, set 
            // paths to 0
            if (grid[i][j] === 1) {
                dp[i][j] = 0;
            }
            else {

                // Accumulate paths from top cell
                if (i > 0)
                    dp[i][j] += dp[i - 1][j];

                // Accumulate paths from left cell
                if (j > 0)
                    dp[i][j] += dp[i][j - 1];
            }
        }
    }

    // Return paths count for the
    // bottom-right cell
    return dp[r - 1][c - 1];
}

const grid = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ];
console.log(uniquePathsWithObstacles(grid));

Output
2

Using Space Optimised DP – O(m*n) Time and O(n) Space

Since each dp[i][j] only depends on the previous row and the current row’s left cell, we can optimize space by using a single 1D array dp of size c (number of columns).

  • dp[j] holds the cumulative paths up to the current cell in the previous row,
  • dp[j – 1] adds paths from the left cell of the current row.
  • After all rows are processed, dp[c-1] will contain the total unique paths to reach the bottom-right corner of the grid.
C++
// C++ code to find unique paths with obstacles 
// using space optimization
#include <bits/stdc++.h>
using namespace std;

int uniquePathsWithObstacles(vector<vector<int>>& grid) {
    int r = grid.size(), c = grid[0].size();

    // Initialize DP array with zeros
    vector<int> dp(c, 0);

    // Set the starting cell if there's no obstacle
    dp[0] = (grid[0][0] == 0) ? 1 : 0;

    // Fill the DP array for each row
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
          
            // If there's an obstacle, set dp[j] to 0
            if (grid[i][j] == 1) {
                dp[j] = 0;
            } else if (j > 0) {
              
                // Add the value from the left cell
                dp[j] += dp[j - 1];
            }
        }
    }

    // Return paths count for the bottom-right cell
    return dp[c - 1];
}

int main() {
  
    vector<vector<int>> grid = { { 0, 0, 0 },
                                 { 0, 1, 0 },
                                 { 0, 0, 0 } };
  
    cout << uniquePathsWithObstacles(grid);
}
Java
// Java code to find unique paths with obstacles 
// using space optimization
class GfG {

    static int uniquePathsWithObstacles(int[][] grid) {
        int r = grid.length, c = grid[0].length;

        // Initialize DP array with zeros
        int[] dp = new int[c];
        
        // Set the starting cell if there's no obstacle
        dp[0] = (grid[0][0] == 0) ? 1 : 0;

        // Fill the DP array for each row
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
              
                // If there's an obstacle, 
                  // set dp[j] to 0
                if (grid[i][j] == 1) {
                    dp[j] = 0;
                } else if (j > 0) {
                  
                    // Add the value from the left cell
                    dp[j] += dp[j - 1];
                }
            }
        }

        // Return paths count for the 
          // bottom-right cell
        return dp[c - 1];
    }

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

        System.out.println(uniquePathsWithObstacles(grid));
    }
}
Python
# Python code to find unique paths with 
# obstacles using space optimization

def uniquePathsWithObstacles(grid):
    r, c = len(grid), len(grid[0])

    # Initialize DP array with zeros
    dp = [0] * c

    # Set the starting cell if there's
    # no obstacle
    dp[0] = 1 if grid[0][0] == 0 else 0

    # Fill the DP array for each row
    for i in range(r):
        for j in range(c):
          
            # If there's an obstacle, 
            # set dp[j] to 0
            if grid[i][j] == 1:
                dp[j] = 0
            elif j > 0:
              
                # Add the value from the
                # left cell
                dp[j] += dp[j - 1]

    # Return paths count for the 
    # bottom-right cell
    return dp[c - 1]

if __name__ == "__main__":
  
    grid = [[0, 0, 0],
            [0, 1, 0],
            [0, 0, 0]]

    print(uniquePathsWithObstacles(grid))
C#
// C# code to find unique paths with obstacles 
// using space optimization
using System;

class GfG {

       static int uniquePathsWithObstacles(int[,] grid) {
        int r = grid.GetLength(0), c = grid.GetLength(1);

        // Initialize DP array with zeros
        int[] dp = new int[c];
        
        // Set the starting cell if there's
          // no obstacle
        dp[0] = (grid[0, 0] == 0) ? 1 : 0;

        // Fill the DP array for each row
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
              
                // If there's an obstacle, 
                  // set dp[j] to 0
                if (grid[i, j] == 1) {
                    dp[j] = 0;
                } else if (j > 0) {
                  
                    // Add the value from the
                      // left cell
                    dp[j] += dp[j - 1];
                }
            }
        }

        // Return paths count for the 
          // bottom-right cell
        return dp[c - 1];
    }

    static void Main() {

        int[,] grid = { { 0, 0, 0 },
                        { 0, 1, 0 },
                        { 0, 0, 0 } };

        Console.WriteLine(uniquePathsWithObstacles(grid));
    }
}
JavaScript
// Javascript code to find unique paths with obstacles
// using space optimization
function uniquePathsWithObstacles(grid) {

    let r = grid.length, c = grid[0].length;

    // Initialize DP array with zeros
    let dp = Array(c).fill(0);

    // Set the starting cell if there's 
    // no obstacle
    dp[0] = grid[0][0] === 0 ? 1 : 0;

    // Fill the DP array for each row
    for (let i = 0; i < r; i++) {
        for (let j = 0; j < c; j++) {

            // If there's an obstacle, set dp[j] to 0
            if (grid[i][j] === 1) {
                dp[j] = 0;
            }
            else if (j > 0) {

                // Add the value from the 
                // left cell
                dp[j] += dp[j - 1];
            }
        }
    }

    // Return paths count for the 
    // bottom-right cell
    return dp[c - 1];
}

const grid = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ];
console.log(uniquePathsWithObstacles(grid));

Output
2


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg