Unique Paths II

Pattern: 2D grid DP

medium

Like Unique Paths, but obstacle cells have 0 paths through them. Fill the same one-row table, setting obstacle cells to 0.

The problem

A grid has obstacles (1) and open cells (0). Moving only right or down from the top-left to the bottom-right, return the number of paths that avoid obstacles.

Think first

  • How many paths go through an obstacle?
  • What if the start is an obstacle?
  • What else changes?

Hints

    Brute force, and why it fails

    Try every path: exponential.

    The key insight

    Setting obstacle cells to 0 blocks every path through them while the rest of the rule stays the same.

    Dry run

    row1 1 1

    grid [[0, 0, 0], [0, 1, 0], [0, 0, 0]]. Row 0: 1 1 1.

    Step 1 of 3

    The plan

    row = [1, 0, ...]
    for each row: for c: row[c] = 0 if obstacle else row[c] + row[c - 1]
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    One pass over the grid.

    Edge cases

    • Start or end blocked: 0.
    • No obstacles: as Unique Paths.
    • A wall of obstacles: 0.
    I've built my logic, show the code

    Java

    class Solution {
        public int uniquePathsWithObstacles(int[][] grid) {
            int C = grid[0].length;
            int[] row = new int[C];
            row[0] = 1;
            for (int[] cells : grid)
                for (int c = 0; c < C; c++) {
                    if (cells[c] == 1) row[c] = 0;  // an obstacle: no way through
                    else if (c > 0) row[c] += row[c - 1];   // from above plus from the left
                }
            return row[C - 1];
        }
    }

    C++

    class Solution {
    public:
        int uniquePathsWithObstacles(vector<vector<int>>& grid) {
            int C = static_cast<int>(grid[0].size());
            vector<long long> row(C, 0);
            row[0] = 1;
            for (const vector<int>& cells : grid)
                for (int c = 0; c < C; c++) {
                    if (cells[c] == 1) row[c] = 0;  // an obstacle: no way through
                    else if (c > 0) row[c] += row[c - 1];   // from above plus from the left
                }
            return static_cast<int>(row[C - 1]);
        }
    };

    Python

    class Solution:
        def uniquePathsWithObstacles(self, grid: list[list[int]]) -> int:
            row = [1] + [0] * (len(grid[0]) - 1)
            for cells in grid:
                for c, blocked in enumerate(cells):
                    if blocked:
                        row[c] = 0                  # an obstacle: no way through
                    elif c:
                        row[c] += row[c - 1]        # from above plus from the left
            return row[-1]

    Common mistakes

    • Initialising the top row to 1 past an obstacle.
    • Forgetting the start cell.

    Similar problems