Unique Paths II

Count the right-and-down paths across a grid when some cells are blocked.

A robot stands on the top-left cell of a grid and wants to reach the bottom-right cell. Each move takes it one cell right or one cell down. The grid is given as obstacleGrid, where 1 marks an obstacle the robot cannot enter and 0 marks a free cell. Return the number of different paths from the start to the finish that avoid every obstacle.

Example 1
Input: obstacleGrid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Output: 2
Explanation: the two paths go around the obstacle in the middle: right, right, down, down, or down, down, right, right.
Example 2
Input: obstacleGrid = [[0, 1], [0, 0]]
Output: 1
Solution

The Idea

Picture a town laid out in square blocks, where you may only walk east or south, and one crossing is closed for roadworks. How many different routes lead to the far corner? Example 1 is such a town with three rows and three columns, and the closed crossing is the cell in the middle.

Here the routes can still be listed by hand. One goes along the top edge and down the right edge: right, right, down, down. The other goes down the left edge and along the bottom: down, down, right, right. Every other route would cross the middle cell. A bigger grid can have tens of thousands of routes, though, so can we count them without listing them?

Look at the last move of any route. To arrive at the finish, the robot comes either from the cell above it or from the cell on its left. So the number of paths to the finish is the number of paths to the cell above plus the number of paths to the cell on the left. The same holds for every cell, so we can write a count into each cell, starting at the top-left.

Look at the picture below, which writes these counts into the grid of Example 1.

The 3 by 3 grid of Example 1 with the number of paths to each cell. The top row and the left column hold 1, the obstacle in row 1, column 1 holds 0, and the finish holds 2, which is 1 from above plus 1 from the left.

The number in each cell counts the paths from the start to that cell. Row 0 holds 1 everywhere, because along the top the robot can only keep moving right. Column 0 holds 1 for the same reason, with moves down. The cell marked obstacle, in row 1, column 1, holds 0, since no path may stand on it.

Now look at the two teal cells. The one in row 1, column 2 gets 1 from above plus 0 from the obstacle on its left, so 1. The one in row 2, column 1 gets 0 from the obstacle above plus 1 from the left, also 1. The cell marked finish adds the two: 1 + 1 = 2, the answer to Example 1.

So the obstacle does not need any special search around it. It simply holds 0, and that 0 adds nothing to the cells right of it and below it. Filling in the grid of counts this way, each cell from two cells that are already filled, is called dynamic programming.

Solution Approach

Turning the picture into code means settling four things: why counting beats following each path, what one count stands for, how obstacles and the grid's edges fit the rule, and how to keep just one row of counts.

Following every path

Why not let the robot try every route? A method that steps right and down from each cell, and adds one each time it reaches the finish, does give the answer. But it follows each path on its own, so its work grows with the number of paths. A grid with no obstacles at all is the Unique Paths problem, and a 10 by 10 one already has 48,620 paths.

The walking also repeats itself. Every path that passes through a cell walks again from that cell to the finish, even though the count from there never changes. Writing down one count per cell means the walk from each cell is worked out only once.

What one count stands for

What exactly is stored? Call the number of paths from the start to the cell in row r, column c, paths(r, c). For a free cell, the last move came from above or from the left, so paths(r, c) = paths(r - 1, c) + paths(r, c - 1). The answer is the count in the bottom-right cell.

Obstacles and the edges

What happens at an obstacle and along the edges? An obstacle cell gets 0, as in the picture, and its 0 flows into the cells to its right and below. The top row has no cell above it, and the left column has no cell on its left, so those missing neighbours count as 0. The start gets 1: the single path that has not moved yet.

Without obstacles the edges are all 1. An obstacle in the top row changes that: every cell to its right gets 0, because the robot cannot go back up to get around it. If the start itself is an obstacle, no cell can be reached and the answer is 0.

Keeping one row of counts

How much of the grid of counts do we need? Filling it row by row, from left to right, means the cell above and the cell on the left are always done when a cell's turn comes. A cell only looks one row up, so older rows are never read again, and one array with a count per column is enough.

The code keeps that row in an array named ways. Before column c of a row is updated, ways[c] still holds the count for the cell above. Its neighbour ways[c - 1] already holds the new count for the cell on the left. Adding the two in place, with ways[c] += ways[c - 1], gives the new count.

Java Solution

The method uniquePathsWithObstacles works in these steps:

  1. First, read the number of columns into n and create the array ways with n counts, all 0. Set ways[0] to 1, the one path to the start cell.
  2. Go through the grid one row at a time with an outer loop. Inside it, a second loop moves c across the columns of that row from left to right.
  3. If the cell holds an obstacle, set ways[c] to 0, so no paths pass through it to the cells below or to the right. An obstacle on the start sets ways[0] to 0 on the very first cell the loops visit.
  4. Otherwise, in any column after the first, add ways[c - 1], the count on the left, to ways[c], which still holds the count from above. Column 0 has nothing on its left, so its count carries down unchanged.
  5. When every row is done, ways[n - 1] holds the number of paths to the bottom-right cell, and the method returns it.

The main method prints each grid row by row, followed by its count, with a helper named show. It tries both examples, a grid with an obstacle under the start, an obstacle on the start, an obstacle on the finish, a single blocked column, and a 10 by 10 grid with no obstacles.

Java
import java.util.Arrays;

public class UniquePathsII {

    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid[0].length;
        int[] ways = new int[n];              // ways[c]: paths to column c of the current row
        ways[0] = 1;                          // one way to stand on the start
        for (int[] row : obstacleGrid) {
            for (int c = 0; c < n; c++) {
                if (row[c] == 1) {
                    ways[c] = 0;              // no path goes through an obstacle
                } else if (c > 0) {
                    ways[c] += ways[c - 1];   // from above (old value) plus from the left
                }
            }
        }
        return ways[n - 1];
    }

    static void show(int[][] grid) {
        for (int[] row : grid) {
            System.out.println(Arrays.toString(row));
        }
        System.out.println("paths: " + uniquePathsWithObstacles(grid));
        System.out.println();
    }

    public static void main(String[] args) {
        show(new int[][] {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}});
        show(new int[][] {{0, 1}, {0, 0}});
        show(new int[][] {{0, 0}, {1, 0}});
        show(new int[][] {{1}});                       // the start is an obstacle
        show(new int[][] {{0, 0}, {0, 1}});            // the finish is an obstacle
        show(new int[][] {{0}, {1}, {0}});             // one column, blocked
        System.out.println("10 x 10, no obstacles, paths: "
            + uniquePathsWithObstacles(new int[10][10]));
    }
}

Running it prints:

Output
[0, 0, 0]
[0, 1, 0]
[0, 0, 0]
paths: 2

[0, 1]
[0, 0]
paths: 1

[0, 0]
[1, 0]
paths: 1

[1]
paths: 0

[0, 0]
[0, 1]
paths: 0

[0]
[1]
[0]
paths: 0

10 x 10, no obstacles, paths: 48620

Example 1 prints paths: 2, the routes along the top and along the left edge, and Example 2 prints paths: 1. In the third grid the obstacle sits in row 1, column 0, right under the start. Going down first is blocked, so a single path is left, right and then down, and the count is 1.

The grid [1] prints paths: 0, because the very first cell visited sets ways[0] to 0 and nothing is ever added to it. The grid with the obstacle on the finish also gives 0, because the finish is the last cell visited and it is set to 0. In the single column, the obstacle in row 1 sets ways[0] to 0, and with no column on the left to add, that 0 carries down to the finish.

The last line shows 48620, the paths through an open 10 by 10 grid, where no cell is held at 0 and every count is the full sum from above and from the left.

Why set an obstacle to 0 instead of skipping it with continue? Skipping leaves the count from the row above in ways[c], so paths seem to pass through the obstacle. A version with continue returns 4 for Example 1 instead of 2, and 2 for [[0, 0], [1, 0]] instead of 1.

Complexity

The work is one visit per cell, and the memory is one row of counts.

  • Time: O(m × n), because the two loops visit each cell of the m rows and n columns once, with one check and at most one addition per cell.
  • Space: O(n), because ways keeps one count per column and each row's counts overwrite the row above, so no m × n grid of counts is stored.

Picking the cheapest path through a grid of costs, instead of counting the paths, is Minimum Path Sum.