Algo-Sim › Dynamic Programming
Unique Paths II
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Unique Paths with obstacles: a blocked cell has 0 paths, and on the first row or column it cuts off everything after it.
Problem
You are given an m × n grid where 1 marks an obstacle and 0 a free cell. A robot starts in the top-left cell and can only move right or down, never onto an obstacle. Return the number of paths to the bottom-right cell.
Constraints
- 1 ≤ m, n ≤ 100
- obstacleGrid[r][c] is 0 or 1
- The answer is at most 2 · 10⁹
Edge cases to test
- An obstacle on the start or the goal:
0 - An obstacle in the first row blocks everything after it
- No obstacles
Follow-up questions
- How do you keep O(n) space?
- One row array: set a blocked cell to 0, otherwise add the cell to its left.
- What if you may move in all four directions?
- Then counting simple paths is a backtracking problem (exponential); shortest paths would use BFS.
Solution
Java
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid[0].length;
int[] dp = new int[n];
dp[0] = 1;
for (int[] row : obstacleGrid) {
for (int c = 0; c < n; c++) {
if (row[c] == 1) dp[c] = 0;
else if (c > 0) dp[c] += dp[c - 1];
}
}
return dp[n - 1];
}Python
def unique_paths_with_obstacles(obstacle_grid):
n = len(obstacle_grid[0])
dp = [0] * n
dp[0] = 1
for row in obstacle_grid:
for c in range(n):
if row[c] == 1: dp[c] = 0
elif c > 0: dp[c] += dp[c - 1]
return dp[n - 1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int n = int(obstacleGrid[0].size());
vector<int> dp(n);
dp[0] = 1;
for (const vector<int> &row : obstacleGrid) {
for (int c = 0; c < n; c++) {
if (row[c] == 1) dp[c] = 0;
else if (c > 0) dp[c] += dp[c - 1];
}
}
return dp[n - 1];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)