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

Edge cases to test

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