Unique paths in a Grid with Obstacles - GeeksforGeeks

05 May, 2022
Given a grid of size m * n, let us assume you are starting at (1, 1) and your goal is to reach (m, n). At any instance, if you are on (x, y), you can either go to (x, y + 1) or (x + 1, y).Now consider if some obstacles are added to the grids. How many unique paths would there be?An obstacle and empty space are marked as 1 and 0 respectively in the grid.
Examples:  
Input: [[0, 0, 0],
        [0, 1, 0],
        [0, 0, 0]]
Output : 2
There is only one obstacle in the middle.
Method 1: Recursion
We have discussed a problem to count 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 that way to reach the bottom right corner is blocked. 
C++
Python3
Javascript
// C++ code to find number of unique paths// in a Matrix#include<bits/stdc++.h>using namespace std; int  UniquePathHelper(int i, int j, int r, int c, vector<vector<int>>& A){    // boundary condition or constraints    if(i == r || j == c){      return 0 ;    }     if(A[i][j] == 1){      return 0 ;    }         // base case    if(i == r-1 && j == c-1){      return 1 ;    }     return  UniquePathHelper(i+1, j, r, c, A) +            UniquePathHelper(i, j+1, r, c, A) ;}  int uniquePathsWithObstacles(vector<vector<int>>& A){         int r = A.size(), c = A[0].size();          return UniquePathHelper(0, 0, r, c, A) ;} // Driver codeint main(){   vector<vector<int>> A = { { 0, 0, 0 },                             { 0, 1, 0 },                             { 0, 0, 0 } };                                 cout << uniquePathsWithObstacles(A) << " \n";                                               }
# Python code to find number of unique paths# in a Matrixdef  UniquePathHelper(i, j, r, c, A):       # boundary condition or constraints    if(i == r or j == c):      return 0         if(A[i][j] == 1):      return 0         # base case    if(i == r-1 and j == c-1):      return 1     return  UniquePathHelper(i+1, j, r, c, A) + UniquePathHelper(i, j+1, r, c, A) def uniquePathsWithObstacles(A):    r,c = len(A),len(A[0])         return UniquePathHelper(0, 0, r, c, A) # Driver codeA = [ [ 0, 0, 0 ],      [ 0, 1, 0 ],      [ 0, 0, 0 ] ]                              print(uniquePathsWithObstacles(A))                                           # This code is contributed by shinjanpatra
<script> // JavaScript code to find number of unique paths// in a Matrixfunction  UniquePathHelper(i, j, r, c, A){       // boundary condition or constraints    if(i == r || j == c)      return 0         if(A[i][j] == 1)      return 0         // base case    if(i == r-1 && j == c-1)      return 1     return  UniquePathHelper(i+1, j, r, c, A) + UniquePathHelper(i, j+1, r, c, A)} function uniquePathsWithObstacles(A){    let r = A.length, c = A[0].length         return UniquePathHelper(0, 0, r, c, A)} // Driver codelet A = [ [ 0, 0, 0 ],      [ 0, 1, 0 ],      [ 0, 0, 0 ] ]                              document.write(uniquePathsWithObstacles(A))                                           // This code is contributed by shinjanpatra </script>
2 
Time Complexity: O(2m*n)
Auxiliary Space: O(m*n) 
Method 2: Using DP
1) Top-Down
The most efficient solution to this problem can be achieved using dynamic programming. Like every dynamic problem concept, we will not recompute the subproblems. A temporary 2D matrix will be constructed and value will be stored using the top-down approach. 
C++
Python3
Javascript
// C++ code to find number of unique paths// in a Matrix#include <bits/stdc++.h>using namespace std; int UniquePathHelper(int i, int j, int r, int c,                     vector<vector<int> >& A,                     vector<vector<int> >& paths){    // boundary condition or constraints    if (i == r || j == c) {        return 0;    }     if (A[i][j] == 1) {        return 0;    }     // base case    if (i == r - 1 && j == c - 1) {        return 1;    }     if (paths[i][j] != -1) {        return paths[i][j];    }     return UniquePathHelper(i + 1, j, r, c, A, paths)           + UniquePathHelper(i, j + 1, r, c, A, paths);} int uniquePathsWithObstacles(vector<vector<int> >& A){     int r = A.size(), c = A[0].size();     // create a 2D-matrix and initializing    // with value 0     vector<vector<int> > paths(r, vector<int>(c, -1));     return UniquePathHelper(0, 0, r, c, A, paths);} // Driver codeint main(){    vector<vector<int> > A        = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } };     cout << uniquePathsWithObstacles(A) << " \n";}
# Python code to find number of unique paths# in a Matrix  def UniquePathHelper(i, j, r, c, A, paths):    # boundary condition or constraints    if (i == r or j == c):        return 0     if (A[i][j] == 1):        return 0     # base case    if (i == r - 1 and j == c - 1):        return 1     if (paths[i][j] != -1):        return paths[i][j]     return UniquePathHelper(i + 1, j, r, c, A, paths) + UniquePathHelper(i, j + 1, r, c, A, paths) def uniquePathsWithObstacles(A):     r,c = len(A),len(A[0])     # create a 2D-matrix and initializing    # with value 0     paths = [[-1 for i in range(c)]for j in range(r)]     return UniquePathHelper(0, 0, r, c, A, paths) # Driver code A  = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ] print(uniquePathsWithObstacles(A)) # code is contributed by shinjanpatra
<script> // JavaScript code to find number of unique paths// in a Matrixfunction UniquePathHelper(i, j, r, c, A, paths){     // boundary condition or constraints    if (i == r || j == c) {        return 0;    }     if (A[i][j] == 1) {        return 0;    }     // base case    if (i == r - 1 && j == c - 1) {        return 1;    }     if (paths[i][j] != -1) {        return paths[i][j];    }     return UniquePathHelper(i + 1, j, r, c, A, paths)           + UniquePathHelper(i, j + 1, r, c, A, paths);} function uniquePathsWithObstacles(A){     let r = A.length, c = A[0].length;     // create a 2D-matrix and initializing    // with value 0    let paths = new Array(c);    for(let i = 0; i < r; i++){        paths[i] = new Array(c).fill(-1);    }     return UniquePathHelper(0, 0, r, c, A, paths);} // Driver codelet A  = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]document.write(uniquePathsWithObstacles(A)) // This code is contributed by shinjanpatra </script>
2 
Time Complexity: O(m*n) 
Auxiliary Space: O(m*n)
2) Bottom-Up
 A temporary 2D matrix will be constructed and value will be stored using the bottom-up approach. 
Create a 2D matrix of the same size as the given matrix to store the results.
Traverse through the created array row-wise and start filling the values in it.
If an obstacle is found, set the value to 0.
For the first row and column, set the value to 1 if an obstacle is not found.
Set the sum of the right and the upper values if an obstacle is not present at that corresponding position in the given matrix
Return the last value of the created 2d matrix
C++
Java
Python
C#
Javascript
// C++ code to find number of unique paths// in a Matrix#include<bits/stdc++.h>using namespace std; int uniquePathsWithObstacles(vector<vector<int>>& A){         int r = A.size(), c = A[0].size();         // create a 2D-matrix and initializing    // with value 0    vector<vector<int>> paths(r, vector<int>(c, 0));         // Initializing the left corner if    // no obstacle there    if (A[0][0] == 0)        paths[0][0] = 1;             // Initializing first column of    // the 2D matrix    for(int i = 1; i < r; i++)    {        // If not obstacle        if (A[i][0] == 0)            paths[i][0] = paths[i-1][0];    }         // Initializing first row of the 2D matrix    for(int j = 1; j < c; j++)    {                 // If not obstacle        if (A[0][j] == 0)            paths[0][j] = paths[0][j - 1];    }            for(int i = 1; i < r; i++)    {        for(int j = 1; j < c; j++)        {                         // If current cell is not obstacle            if (A[i][j] == 0)                paths[i][j] = paths[i - 1][j] +                              paths[i][j - 1];        }     }         // Returning the corner value    // of the matrix    return paths[r - 1];} // Driver codeint main(){   vector<vector<int>> A = { { 0, 0, 0 },                             { 0, 1, 0 },                             { 0, 0, 0 } };                                 cout << uniquePathsWithObstacles(A) << " \n";                                               } // This code is contributed by ajaykr00kj
// Java code to find number of unique paths// in a Matrixpublic class Main{  static int uniquePathsWithObstacles(int[][] A)  {     int r = 3, c = 3;     // create a 2D-matrix and initializing    // with value 0    int[][] paths = new int[r];    for(int i = 0; i < r; i++)    {      for(int j = 0; j < c; j++)      {        paths[i][j] = 0;      }    }     // Initializing the left corner if    // no obstacle there    if (A[0][0] == 0)      paths[0][0] = 1;     // Initializing first column of    // the 2D matrix    for(int i = 1; i < r; i++)    {      // If not obstacle      if (A[i][0] == 0)        paths[i][0] = paths[i - 1][0];    }     // Initializing first row of the 2D matrix    for(int j = 1; j < c; j++)    {       // If not obstacle      if (A[0][j] == 0)        paths[0][j] = paths[0][j - 1];    }       for(int i = 1; i < r; i++)    {      for(int j = 1; j < c; j++)      {         // If current cell is not obstacle        if (A[i][j] == 0)          paths[i][j] = paths[i - 1][j] +          paths[i][j - 1];      }     }     // Returning the corner value    // of the matrix    return paths[r - 1];  }   // Driver code  public static void main(String[] args) {    int[][] A = { { 0, 0, 0 },                 { 0, 1, 0 },                 { 0, 0, 0 } };     System.out.print(uniquePathsWithObstacles(A));  }} // This code is contributed by divyeshrabadiya07.
# Python code to find number of unique paths in a# matrix with obstacles. def uniquePathsWithObstacles(A):     # create a 2D-matrix and initializing with value 0    paths = [[0]*len(A[0]) for i in A]         # initializing the left corner if no obstacle there    if A[0][0] == 0:        paths[0][0] = 1         # initializing first column of the 2D matrix    for i in range(1, len(A)):                 # If not obstacle        if A[i][0] == 0:            paths[i][0] = paths[i-1][0]                 # initializing first row of the 2D matrix    for j in range(1, len(A[0])):                 # If not obstacle        if A[0][j] == 0:            paths[0][j] = paths[0][j-1]                 for i in range(1, len(A)):        for j in range(1, len(A[0])):             # If current cell is not obstacle            if A[i][j] == 0:                paths[i][j] = paths[i-1][j] + paths[i][j-1]     # returning the corner value of the matrix    return paths[-1][-1]  # Driver CodeA = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]print(uniquePathsWithObstacles(A))
// C# code to find number of unique paths// in a Matrixusing System;class GFG {   static int uniquePathsWithObstacles(int[,] A)  {     int r = 3, c = 3;     // create a 2D-matrix and initializing    // with value 0    int[,] paths = new int[r,c];    for(int i = 0; i < r; i++)    {      for(int j = 0; j < c; j++)      {        paths[i, j] = 0;      }    }     // Initializing the left corner if    // no obstacle there    if (A[0, 0] == 0)      paths[0, 0] = 1;     // Initializing first column of    // the 2D matrix    for(int i = 1; i < r; i++)    {      // If not obstacle      if (A[i, 0] == 0)        paths[i, 0] = paths[i - 1, 0];    }     // Initializing first row of the 2D matrix    for(int j = 1; j < c; j++)    {       // If not obstacle      if (A[0, j] == 0)        paths[0, j] = paths[0, j - 1];    }       for(int i = 1; i < r; i++)    {      for(int j = 1; j < c; j++)      {         // If current cell is not obstacle        if (A[i, j] == 0)          paths[i, j] = paths[i - 1, j] +          paths[i, j - 1];      }     }     // Returning the corner value    // of the matrix    return paths[r - 1, c - 1];  }   // Driver code  static void Main() {    int[,] A = { { 0, 0, 0 },                { 0, 1, 0 },                { 0, 0, 0 } };     Console.WriteLine(uniquePathsWithObstacles(A));  }} // This code is contributed by divyesh072019.
<script>    // Javascript code to find number of unique paths    // in a Matrix         function uniquePathsWithObstacles(A)    {       let r = 3, c = 3;       // create a 2D-matrix and initializing      // with value 0      let paths = new Array(r);      for(let i = 0; i < r; i++)      {          paths[i] = new Array(c);        for(let j = 0; j < c; j++)        {          paths[i][j] = 0;        }      }       // Initializing the left corner if      // no obstacle there      if (A[0][0] == 0)        paths[0][0] = 1;       // Initializing first column of      // the 2D matrix      for(let i = 1; i < r; i++)      {        // If not obstacle        if (A[i][0] == 0)          paths[i][0] = paths[i - 1][0];      }       // Initializing first row of the 2D matrix      for(let j = 1; j < c; j++)      {         // If not obstacle        if (A[0][j] == 0)          paths[0][j] = paths[0][j - 1];      }        for(let i = 1; i < r; i++)      {        for(let j = 1; j < c; j++)        {           // If current cell is not obstacle          if (A[i][j] == 0)            paths[i][j] = paths[i - 1][j] +            paths[i][j - 1];        }      }       // Returning the corner value      // of the matrix      return paths[r - 1];    }           let A = [ [ 0, 0, 0 ],             [ 0, 1, 0 ],             [ 0, 0, 0 ] ];      document.write(uniquePathsWithObstacles(A));         // This code is contributed by suresh07.</script>
2 
This article is contributed by Rishabh Bansal. 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
In this method, we will use the given ‘A’ 2D matrix to store the previous answer using the bottom-up approach.
Approach
Start traversing through the given ‘A’ 2D matrix row-wise and fill the values in it.
For the first row and the first column set the value to 1 if an obstacle is not found.
For the first row and first column, if an obstacle is found then start filling 0 till the last index in that particular row or column.
Now start traversing from the second row and column ( eg: A[ 1 ][ 1 ]).
If an obstacle is found, set 0 at particular Grid ( eg: A[ i ][ j ] ), otherwise set sum of upper and left values at A[ i ][ j ].
Return the last value of the 2D matrix.
Below is the implementation of the above approach. 
C++
Java
Python3
Javascript
// CPP program for the above approach #include <bits/stdc++.h>using namespace std; int uniquePathsWithObstacles(vector<vector<int> >& A){     int r = A.size();    int c = A[0].size();     // If obstacle is at starting position    if (A[0][0])        return 0;     //  Initializing starting position    A[0][0] = 1;     // first row all are '1' until obstacle    for (int j = 1; j < c; j++) {         if (A[0][j] == 0) {            A[0][j] = A[0][j - 1];        }        else {            // No ways to reach at this index            A[0][j] = 0;        }    }     // first column all are '1' until obstacle    for (int i = 1; i < r; i++) {         if (A[i][0] == 0) {            A[i][0] = A[i - 1][0];        }        else {            // No ways to reach at this index            A[i][0] = 0;        }    }     for (int i = 1; i < r; i++) {         for (int j = 1; j < c; j++) {            // If current cell has no obstacle            if (A[i][j] == 0) {                 A[i][j] = A[i - 1][j] + A[i][j - 1];            }            else {                // No ways to reach at this index                A[i][j] = 0;            }        }    }     // returning the bottom right    // corner of Grid    return A[r - 1];} // Driver Code int main(){     vector<vector<int> > A        = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } };     cout << uniquePathsWithObstacles(A) << "\n";     return 0;}// This code is contributed by hemantraj712
// Java program for the above approachclass GFG {     static int uniquePathsWithObstacles(int[][] A)    {         int r = A.length;        int c = A[0].length;         // If obstacle is at starting position        if (A[0][0] != 0)            return 0;         //  Initializing starting position        A[0][0] = 1;         // first row all are '1' until obstacle        for (int j = 1; j < c; j++) {             if (A[0][j] == 0) {                A[0][j] = A[0][j - 1];            }            else {                // No ways to reach at this index                A[0][j] = 0;            }        }         // first column all are '1' until obstacle        for (int i = 1; i < r; i++) {             if (A[i][0] == 0) {                A[i][0] = A[i - 1][0];            }            else {                // No ways to reach at this index                A[i][0] = 0;            }        }         for (int i = 1; i < r; i++)        {             for (int j = 1; j < c; j++)            {                               // If current cell has no obstacle                if (A[i][j] == 0) {                     A[i][j] = A[i - 1][j] + A[i][j - 1];                }                else {                    // No ways to reach at this index                    A[i][j] = 0;                }            }        }         // returning the bottom right        // corner of Grid        return A[r - 1];    }   // Driver code    public static void main(String[] args)    {        int[][] A            = { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } };         System.out.print(uniquePathsWithObstacles(A));    }} // This code is contributed by rajsanghavi9.
# Python program for the above approach  def uniquePathsWithObstacles(A):     r = len(A)    c = len(A[0])     # If obstacle is at starting position    if (A[0][0]):        return 0     #  Initializing starting position    A[0][0] = 1     # first row all are '1' until obstacle    for j in range(1,c):         if (A[0][j] == 0):            A[0][j] = A[0][j - 1]        else:            # No ways to reach at this index            A[0][j] = 0     # first column all are '1' until obstacle    for i in range(1,r):         if (A[i][0] == 0):            A[i][0] = A[i - 1][0]        else:            # No ways to reach at this index            A[i][0] = 0     for i in range(1,r):         for j in range(1,c):            # If current cell has no obstacle            if (A[i][j] == 0):                 A[i][j] = A[i - 1][j] + A[i][j - 1]            else:                # No ways to reach at this index                A[i][j] = 0     # returning the bottom right    # corner of Grid    return A[r - 1] # Driver Code A = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ] print(uniquePathsWithObstacles(A)) # This code is contributed by shinjanpatra
<script> // JavaScript program for the above approachfunction uniquePathsWithObstacles(A){     let r = A.length    let c = A[0].length     // If obstacle is at starting position    if (A[0][0])        return 0     //  Initializing starting position    A[0][0] = 1     // first row all are '1' until obstacle    for(let j = 1; j < c; j++)    {        if (A[0][j] == 0)            A[0][j] = A[0][j - 1]        else            // No ways to reach at this index            A[0][j] = 0    }     // first column all are '1' until obstacle    for(let i = 1; i < r; i++){         if (A[i][0] == 0)            A[i][0] = A[i - 1][0]        else            // No ways to reach at this index            A[i][0] = 0    }    for(let i = 1; i < r; i++){       for(let j = 1; j < c; j++){            // If current cell has no obstacle            if (A[i][j] == 0)                 A[i][j] = A[i - 1][j] + A[i][j - 1]            else                // No ways to reach at this index                A[i][j] = 0      }   }     // returning the bottom right    // corner of Grid    return A[r - 1]} // Driver Codelet A = [ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]document.write(uniquePathsWithObstacles(A),"</br>") // This code is contributed by shinjanpatra </script>
2
Time Complexity: O(m*n)  Auxiliary Space: O(1)
ajaykr00kj
bluecoder_
divyesh072019
divyeshrabadiya07
snape_here
suresh07
hemantraj712
TECHWorld1
punamsingh628700
rajsanghavi9
sooda367
mailtoproma
prasanna1995
shinjanpatra
Dynamic Programming
Matrix
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7