Open In App

Unique paths in a Grid with Obstacles

Last Updated : 23 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a matrix mat[][] of size n * m, where mat[i][j] = 1 indicates an obstacle and mat[i][j] = 0 indicates an empty space. The task is to find the number of unique paths to reach (n-1, m-1) starting from (0, 0). You are allowed to move in the right or downward direction.

Note: In the grid, cells marked with 1 represent obstacles, and 0 represent free space. Movement is restricted to only right (i, j+1) or down (i+1, j) from the current cell (i, j).

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^(n*m)) Time and O(n+m) Space

We have discussed the problem of counting the number of unique paths in a matrix when no obstacle was present in the matrix. But here the situation is quite different. While moving through the matrix, 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 matrix[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:

  • uniquePaths(i, j, r, c, matrix) = uniquePaths(i+1, j, r, c, matrix) + uniquePaths(i, j+1, r, c, matrix)
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 uniquePathsRecur(int i, int j, vector<vector<int>>& grid) {
    int r = grid.size(), c = grid[0].size();

	// 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 uniquePathsRecur(i+1, j, grid) +
	       uniquePathsRecur(i, j+1, grid);
}

// Function to find unique paths with obstacles
int uniquePaths(vector<vector<int>>& grid) {
	return uniquePathsRecur(0, 0, grid);
}

int main() {

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

	cout << uniquePaths(grid);
}
Java
// Java code to find number of unique paths
// using Recursion

class GfG {
    
    // Helper function to find unique paths recursively
    static int uniquePathsRecur(int i, int j, int[][] grid) {
        int r = grid.length, c = grid[0].length;

        // 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 uniquePathsRecur(i+1, j, grid) +
               uniquePathsRecur(i, j+1, grid);
    }

    // Function to find unique paths with obstacles
    static int uniquePaths(int[][] grid) {
        return uniquePathsRecur(0, 0, grid);
    }

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

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

# Helper function to find unique paths recursively
def uniquePathsRecur(i, j, grid):
    r = len(grid)
    c = len(grid[0])

    # 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 uniquePathsRecur(i+1, j, grid) + uniquePathsRecur(i, j+1, grid)

# Function to find unique paths with obstacles
def uniquePaths(grid):
    return uniquePathsRecur(0, 0, grid)

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

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

using System;

class GfG {
    
    // Helper function to find unique paths recursively
    static int uniquePathsRecur(int i, int j, int[,] grid) {
        int r = grid.GetLength(0), c = grid.GetLength(1);

        // 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 uniquePathsRecur(i+1, j, grid) +
               uniquePathsRecur(i, j+1, grid);
    }

    // Function to find unique paths with obstacles
    static int uniquePaths(int[,] grid) {
        return uniquePathsRecur(0, 0, grid);
    }

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

        Console.WriteLine(uniquePaths(grid));
    }
}
JavaScript
// JavaScript code to find number of unique paths
// using Recursion

// Helper function to find unique paths recursively
function uniquePathsRecur(i, j, grid) {
    const r = grid.length, c = grid[0].length;

    // 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 uniquePathsRecur(i+1, j, grid) + 
    uniquePathsRecur(i, j+1, grid);
}

// Function to find unique paths with obstacles
function uniquePaths(grid) {
    return uniquePathsRecur(0, 0, grid);
}

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

console.log(uniquePaths(grid));

Output
2

Using Top-Down DP(Memoization) - O(n*m) Time and O(n*m) 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 matrix with obstacles, we observe that many subproblems are computed multiple times. For instance, when computing uniquePaths(i, j), where i and j represent the current cell in the matrix, 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 matrix. 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 matrix. 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
int uniquePathsRecur(int i, int j, vector<vector<int>>& grid, 
vector<vector<int>>& memo) {
    int r = grid.size(), c = grid[0].size();
    
    // 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 already computed, return the stored result
    if(memo[i][j] != -1) {
        return memo[i][j];
    }
    
    // Compute and store the result
    memo[i][j] = uniquePathsRecur(i+1, j, grid, memo) + 
                 uniquePathsRecur(i, j+1, grid, memo);
    
    return memo[i][j];
}

// Function to find unique paths with obstacles
int uniquePaths(vector<vector<int>>& grid) {
    int n = grid.size(), m = grid[0].size();
    
    // Initialize memoization table with -1
    vector<vector<int>> memo(n, vector<int>(m, -1));
    
    return uniquePathsRecur(0, 0, grid, memo);
}

int main() {
    vector<vector<int>> grid = {
        { 0, 0, 0 },
        { 0, 1, 0 },
        { 0, 0, 0 }
    };
    
    cout << uniquePaths(grid);
    
    return 0;
}
Java
// Java code to find number of unique paths
// using Memoization

import java.util.*;

class GfG {
    
    // Helper function to find unique paths
    static int uniquePathsRecur(int i, int j, int[][] grid, int[][] memo) {
        int r = grid.length, c = grid[0].length;
        
        // 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 already computed, return the stored result
        if(memo[i][j] != -1) {
            return memo[i][j];
        }
        
        // Compute and store the result
        memo[i][j] = uniquePathsRecur(i+1, j, grid, memo) + 
                     uniquePathsRecur(i, j+1, grid, memo);
        
        return memo[i][j];
    }
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        
        // Initialize memoization table with -1
        int[][] memo = new int[n][m];
        for(int i = 0; i < n; i++) {
            Arrays.fill(memo[i], -1);
        }
        
        return uniquePathsRecur(0, 0, grid, memo);
    }
    
    public static void main(String[] args) {
        int[][] grid = {
            { 0, 0, 0 },
            { 0, 1, 0 },
            { 0, 0, 0 }
        };
        
        System.out.println(uniquePaths(grid));
    }
}
Python
# Python code to find number of unique paths
# using Memoization

# Helper function to find unique paths
def uniquePathsRecur(i, j, grid, memo):
    r = len(grid)
    c = len(grid[0])
    
    # 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 already computed, return the stored result
    if memo[i][j] != -1:
        return memo[i][j]
    
    # Compute and store the result
    memo[i][j] = uniquePathsRecur(i+1, j, grid, memo) + \
                 uniquePathsRecur(i, j+1, grid, memo)
    
    return memo[i][j]

# Function to find unique paths with obstacles
def uniquePaths(grid):
    n = len(grid)
    m = len(grid[0])
    
    # Initialize memoization table with -1
    memo = [[-1 for _ in range(m)] for _ in range(n)]
    
    return uniquePathsRecur(0, 0, grid, memo)

if __name__ == "__main__":
    grid = [
        [0, 0, 0],
        [0, 1, 0],
        [0, 0, 0]
    ]
    
    print(uniquePaths(grid))
C#
// C# code to find number of unique paths
// using Memoization

using System;

class GfG {
    
    // Helper function to find unique paths
    static int uniquePathsRecur(int i, int j, int[,] grid, int[,] memo) {
        int r = grid.GetLength(0), c = grid.GetLength(1);
        
        // 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 already computed, return the stored result
        if(memo[i, j] != -1) {
            return memo[i, j];
        }
        
        // Compute and store the result
        memo[i, j] = uniquePathsRecur(i+1, j, grid, memo) + 
                     uniquePathsRecur(i, j+1, grid, memo);
        
        return memo[i, j];
    }
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[,] grid) {
        int n = grid.GetLength(0), m = grid.GetLength(1);
        
        // Initialize memoization table with -1
        int[,] memo = new int[n, m];
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                memo[i, j] = -1;
            }
        }
        
        return uniquePathsRecur(0, 0, grid, memo);
    }
    
    static void Main() {
        int[,] grid = {
            { 0, 0, 0 },
            { 0, 1, 0 },
            { 0, 0, 0 }
        };
        
        Console.WriteLine(uniquePaths(grid));
    }
}
JavaScript
// JavaScript code to find number of unique paths
// using Memoization

// Helper function to find unique paths
function uniquePathsRecur(i, j, grid, memo) {
    const r = grid.length, c = grid[0].length;
    
    // 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 already computed, return the stored result
    if(memo[i][j] != -1) {
        return memo[i][j];
    }
    
    // Compute and store the result
    memo[i][j] = uniquePathsRecur(i+1, j, grid, memo) + 
                 uniquePathsRecur(i, j+1, grid, memo);
    
    return memo[i][j];
}

// Function to find unique paths with obstacles
function uniquePaths(grid) {
    const n = grid.length, m = grid[0].length;
    
    // Initialize memoization table with -1
    const memo = Array(n).fill().map(() => Array(m).fill(-1));
    
    return uniquePathsRecur(0, 0, grid, memo);
}

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

console.log(uniquePaths(grid));

Output
2

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

The idea is to fill the DP table based on previous values. For each cell, the number of unique paths depends on the next and below cell. The table is filled in an iterative manner from i = n-1 to i = 1 and j = m-1 to j = 1.

The dynamic programming relation is as follows: 

  • dp[i][j] = dp[i+1][j] + dp[i][j+1]
C++
// C++ code to find number of unique paths
// using Tabulation
#include <bits/stdc++.h>
using namespace std;

// Function to find unique paths with obstacles
int uniquePaths(vector<vector<int>>& grid) {
    int n = grid.size(), m = grid[0].size();
    
    // If starting or ending cell is an obstacle, return 0
    if(grid[0][0] == 1 || grid[n-1][m-1] == 1) {
        return 0;
    }
    
    // Initialize dp table with 0
    vector<vector<int>> dp(n, vector<int>(m, 0));
    dp[n-1][m-1] = 1;
    
    // Fill the bottom row
    for(int j = m-2; j >= 0; j--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[n-1][j] == 1) {
            break;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[n-1][j] = 1;
        }
    }
    
    // Fill the rightmost column
    for(int i = n-2; i >= 0; i--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[i][m-1] == 1) {
            break;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[i][m-1] = 1;
        }
    }
    
    // Fill the inner cells bottom-up and right-left
    for(int i = n-2; i >= 0; i--) {
        for(int j = m-2; j >= 0; j--) {
            if(grid[i][j] == 0) {
                
                // Number of paths = sum of paths from the 
                // cell below and the cell to the right
                dp[i][j] = dp[i+1][j] + dp[i][j+1];
            }
        }
    }
    
    return dp[0][0];
}

int main() {
    vector<vector<int>> grid = {
        { 0, 0, 0 },
        { 0, 1, 0 },
        { 0, 0, 0 }
    };
    
    cout << uniquePaths(grid);
    
    return 0;
}
Java
// Java code to find number of unique paths
// using Tabulation

class GfG {
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        
        // If starting or ending cell is an obstacle, return 0
        if(grid[0][0] == 1 || grid[n-1][m-1] == 1) {
            return 0;
        }
        
        // Initialize dp table with 0
        int[][] dp = new int[n][m];
        dp[n-1][m-1] = 1;
        
        // Fill the bottom row
        for(int j = m-2; j >= 0; j--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[n-1][j] == 1) {
                break;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[n-1][j] = 1;
            }
        }
        
        // Fill the rightmost column
        for(int i = n-2; i >= 0; i--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[i][m-1] == 1) {
                break;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[i][m-1] = 1;
            }
        }
        
        // Fill the inner cells bottom-up and right-left
        for(int i = n-2; i >= 0; i--) {
            for(int j = m-2; j >= 0; j--) {
                if(grid[i][j] == 0) {
                    
                    // Number of paths = sum of paths from the 
                    // cell below and the cell to the right
                    dp[i][j] = dp[i+1][j] + dp[i][j+1];
                }
            }
        }
        
        return dp[0][0];
    }

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

# Function to find unique paths with obstacles
def uniquePaths(grid):
    n = len(grid)
    m = len(grid[0])
    
    # If starting or ending cell is an obstacle, return 0
    if grid[0][0] == 1 or grid[n-1][m-1] == 1:
        return 0
    
    # Initialize dp table with 0
    dp = [[0]*m for _ in range(n)]
    dp[n-1][m-1] = 1
    
    # Fill the bottom row
    for j in range(m-2, -1, -1):
        
        # As this is an obstacle, no paths will 
        # exist from this cell.
        if grid[n-1][j] == 1:
            break
        
        # Otherwise, a straight path to 
        # n-1, m-1 exists 
        else:
            dp[n-1][j] = 1
    
    # Fill the rightmost column
    for i in range(n-2, -1, -1):
        
        # As this is an obstacle, no paths will 
        # exist from this cell.
        if grid[i][m-1] == 1:
            break
        
        # Otherwise, a straight path to 
        # n-1, m-1 exists 
        else:
            dp[i][m-1] = 1
    
    # Fill the inner cells bottom-up and right-left
    for i in range(n-2, -1, -1):
        for j in range(m-2, -1, -1):
            if grid[i][j] == 0:
                
                # Number of paths = sum of paths from the 
                # cell below and the cell to the right
                dp[i][j] = dp[i+1][j] + dp[i][j+1]
    
    return dp[0][0]

if __name__ == "__main__":
    grid = [
        [ 0, 0, 0 ],
        [ 0, 1, 0 ],
        [ 0, 0, 0 ]
    ]
    
    print(uniquePaths(grid))
C#
// C# code to find number of unique paths
// using Tabulation

using System;

class GfG {
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[,] grid) {
        int n = grid.GetLength(0), m = grid.GetLength(1);
        
        // If starting or ending cell is an obstacle, return 0
        if(grid[0,0] == 1 || grid[n-1,m-1] == 1) {
            return 0;
        }
        
        // Initialize dp table with 0
        int[,] dp = new int[n,m];
        dp[n-1,m-1] = 1;
        
        // Fill the bottom row
        for(int j = m-2; j >= 0; j--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[n-1,j] == 1) {
                break;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[n-1,j] = 1;
            }
        }
        
        // Fill the rightmost column
        for(int i = n-2; i >= 0; i--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[i,m-1] == 1) {
                break;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[i,m-1] = 1;
            }
        }
        
        // Fill the inner cells bottom-up and right-left
        for(int i = n-2; i >= 0; i--) {
            for(int j = m-2; j >= 0; j--) {
                if(grid[i,j] == 0) {
                    
                    // Number of paths = sum of paths from the 
                    // cell below and the cell to the right
                    dp[i,j] = dp[i+1,j] + dp[i,j+1];
                }
            }
        }
        
        return dp[0,0];
    }

    public static void Main(string[] args) {
        int[,] grid = {
            { 0, 0, 0 },
            { 0, 1, 0 },
            { 0, 0, 0 }
        };
        
        Console.WriteLine(uniquePaths(grid));
    }
}
JavaScript
// JavaScript code to find number of unique paths
// using Tabulation

// Function to find unique paths with obstacles
function uniquePaths(grid) {
    const n = grid.length, m = grid[0].length;
    
    // If starting or ending cell is an obstacle, return 0
    if(grid[0][0] === 1 || grid[n-1][m-1] === 1) {
        return 0;
    }
    
    // Initialize dp table with 0
    const dp = Array(n).fill().map(() => Array(m).fill(0));
    dp[n-1][m-1] = 1;
    
    // Fill the bottom row
    for(let j = m-2; j >= 0; j--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[n-1][j] === 1) {
            break;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[n-1][j] = 1;
        }
    }
    
    // Fill the rightmost column
    for(let i = n-2; i >= 0; i--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[i][m-1] === 1) {
            break;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[i][m-1] = 1;
        }
    }
    
    // Fill the inner cells bottom-up and right-left
    for(let i = n-2; i >= 0; i--) {
        for(let j = m-2; j >= 0; j--) {
            if(grid[i][j] === 0) {
                
                // Number of paths = sum of paths from the 
                // cell below and the cell to the right
                dp[i][j] = dp[i+1][j] + dp[i][j+1];
            }
        }
    }
    
    return dp[0][0];
}

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

console.log(uniquePaths(grid));

Output
2

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

In previous approach of dynamic programming we have derive the relation between states as given below:

  • dp[i][j] = dp[i+1][j] + dp[i][j+1]

If we observe that for calculating current dp[i][j] state we only need next row dp[i+1][j] and next cells value. There is no need to store all the next states just one next state is used to compute result.

Illustration:

C++
// C++ code to find number of unique paths
// using Space-Optimized Tabulation
#include <bits/stdc++.h>
using namespace std;

// Function to find unique paths with obstacles
int uniquePaths(vector<vector<int>>& grid) {
    int n = grid.size(), m = grid[0].size();
    
    // If starting or ending cell is an obstacle, return 0
    if(grid[0][0] == 1 || grid[n-1][m-1] == 1) {
        return 0;
    }
    
    // Initialize dp array with 0
    vector<int> dp(m, 0);
    
    // Set the value for the bottom-right cell
    dp[m-1] = 1;
    
    // Fill the bottom row first
    for(int j = m-2; j >= 0; j--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[n-1][j] == 1) {
            dp[j] = 0;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[j] = dp[j+1];
        }
    }
    
    // Process each row from bottom to top
    for(int i = n-2; i >= 0; i--) {
        
        // Process the rightmost column of the current row
        if(grid[i][m-1] == 1) {
            dp[m-1] = 0;
        }
        
        // Process each cell from right to left
        for(int j = m-2; j >= 0; j--) {
            
            // If current cell is an obstacle, paths = 0
            if(grid[i][j] == 1) {
                dp[j] = 0;
            }
            
            // Otherwise, paths = sum of right and down paths
            else {
                dp[j] = dp[j] + dp[j+1];
            }
        }
    }
    
    return dp[0];
}

int main() {
    vector<vector<int>> grid = {
        { 0, 0, 0 },
        { 0, 1, 0 },
        { 0, 0, 0 }
    };
    
    cout << uniquePaths(grid);
    
    return 0;
}
Java
// Java code to find number of unique paths
// using Space-Optimized Tabulation

class GfG {
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[][] grid) {
        int n = grid.length, m = grid[0].length;
        
        // If starting or ending cell is an obstacle, return 0
        if(grid[0][0] == 1 || grid[n-1][m-1] == 1) {
            return 0;
        }
        
        // Initialize dp array with 0
        int[] dp = new int[m];
        
        // Set the value for the bottom-right cell
        dp[m-1] = 1;
        
        // Fill the bottom row first
        for(int j = m-2; j >= 0; j--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[n-1][j] == 1) {
                dp[j] = 0;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[j] = dp[j+1];
            }
        }
        
        // Process each row from bottom to top
        for(int i = n-2; i >= 0; i--) {
            
            // Process the rightmost column of the current row
            if(grid[i][m-1] == 1) {
                dp[m-1] = 0;
            }
            
            // Process each cell from right to left
            for(int j = m-2; j >= 0; j--) {
                
                // If current cell is an obstacle, paths = 0
                if(grid[i][j] == 1) {
                    dp[j] = 0;
                }
                
                // Otherwise, paths = sum of right and down paths
                else {
                    dp[j] = dp[j] + dp[j+1];
                }
            }
        }
        
        return dp[0];
    }

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

# Function to find unique paths with obstacles
def uniquePaths(grid):
    n = len(grid)
    m = len(grid[0])
    
    # If starting or ending cell is an obstacle, return 0
    if grid[0][0] == 1 or grid[n-1][m-1] == 1:
        return 0
    
    # Initialize dp array with 0
    dp = [0] * m
    
    # Set the value for the bottom-right cell
    dp[m-1] = 1
    
    # Fill the bottom row first
    for j in range(m-2, -1, -1):
        
        # As this is an obstacle, no paths will 
        # exist from this cell.
        if grid[n-1][j] == 1:
            dp[j] = 0
        
        # Otherwise, a straight path to 
        # n-1, m-1 exists 
        else:
            dp[j] = dp[j+1]
    
    # Process each row from bottom to top
    for i in range(n-2, -1, -1):
        
        # Process the rightmost column of the current row
        if grid[i][m-1] == 1:
            dp[m-1] = 0
        
        # Process each cell from right to left
        for j in range(m-2, -1, -1):
            
            # If current cell is an obstacle, paths = 0
            if grid[i][j] == 1:
                dp[j] = 0
            
            # Otherwise, paths = sum of right and down paths
            else:
                dp[j] = dp[j] + dp[j+1]
    
    return dp[0]

if __name__ == "__main__":
    grid = [
        [ 0, 0, 0 ],
        [ 0, 1, 0 ],
        [ 0, 0, 0 ]
    ]
    
    print(uniquePaths(grid))
C#
// C# code to find number of unique paths
// using Space-Optimized Tabulation

using System;

class GfG {
    
    // Function to find unique paths with obstacles
    static int uniquePaths(int[,] grid) {
        int n = grid.GetLength(0), m = grid.GetLength(1);
        
        // If starting or ending cell is an obstacle, return 0
        if(grid[0,0] == 1 || grid[n-1,m-1] == 1) {
            return 0;
        }
        
        // Initialize dp array with 0
        int[] dp = new int[m];
        
        // Set the value for the bottom-right cell
        dp[m-1] = 1;
        
        // Fill the bottom row first
        for(int j = m-2; j >= 0; j--) {
            
            // As this is an obstacle, no paths will 
            // exist from this cell.
            if(grid[n-1,j] == 1) {
                dp[j] = 0;
            }
            
            // Otherwise, a straight path to 
            // n-1, m-1 exists 
            else {
                dp[j] = dp[j+1];
            }
        }
        
        // Process each row from bottom to top
        for(int i = n-2; i >= 0; i--) {
            
            // Process the rightmost column of the current row
            if(grid[i,m-1] == 1) {
                dp[m-1] = 0;
            }
            
            // Process each cell from right to left
            for(int j = m-2; j >= 0; j--) {
                
                // If current cell is an obstacle, paths = 0
                if(grid[i,j] == 1) {
                    dp[j] = 0;
                }
                
                // Otherwise, paths = sum of right and down paths
                else {
                    dp[j] = dp[j] + dp[j+1];
                }
            }
        }
        
        return dp[0];
    }

    public static void Main(string[] args) {
        int[,] grid = {
            { 0, 0, 0 },
            { 0, 1, 0 },
            { 0, 0, 0 }
        };
        
        Console.WriteLine(uniquePaths(grid));
    }
}
JavaScript
// JavaScript code to find number of unique paths
// using Space-Optimized Tabulation

// Function to find unique paths with obstacles
function uniquePaths(grid) {
    const n = grid.length, m = grid[0].length;
    
    // If starting or ending cell is an obstacle, return 0
    if(grid[0][0] === 1 || grid[n-1][m-1] === 1) {
        return 0;
    }
    
    // Initialize dp array with 0
    const dp = new Array(m).fill(0);
    
    // Set the value for the bottom-right cell
    dp[m-1] = 1;
    
    // Fill the bottom row first
    for(let j = m-2; j >= 0; j--) {
        
        // As this is an obstacle, no paths will 
        // exist from this cell.
        if(grid[n-1][j] === 1) {
            dp[j] = 0;
        }
        
        // Otherwise, a straight path to 
        // n-1, m-1 exists 
        else {
            dp[j] = dp[j+1];
        }
    }
    
    // Process each row from bottom to top
    for(let i = n-2; i >= 0; i--) {
        
        // Process the rightmost column of the current row
        if(grid[i][m-1] === 1) {
            dp[m-1] = 0;
        }
        
        // Process each cell from right to left
        for(let j = m-2; j >= 0; j--) {
            
            // If current cell is an obstacle, paths = 0
            if(grid[i][j] === 1) {
                dp[j] = 0;
            }
            
            // Otherwise, paths = sum of right and down paths
            else {
                dp[j] = dp[j] + dp[j+1];
            }
        }
    }
    
    return dp[0];
}

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

console.log(uniquePaths(grid));

Output
2

Next Article

Similar Reads