Unique paths in a Grid with Obstacles
Last Updated :
23 May, 2025
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:
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));
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));
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));
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));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem