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
Example 1
Output: 2
Explanation: the two paths go around the obstacle in the middle: right, right, down, down, or down, down, right, right.
Example 2
Output: 1
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 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
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)
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 waysways[c]ways[c - 1]ways[c] += ways[c - 1]
Java Solution
The method uniquePathsWithObstacles
- First, read the number of columns into
and create the arrayn withways counts, all 0. Setn to 1, the one path to the start cell.ways[0] - Go through the grid one row at a time with an outer loop. Inside it, a second loop moves
across the columns of that row from left to right.c - If the cell holds an obstacle, set
to 0, so no paths pass through it to the cells below or to the right. An obstacle on the start setsways[c] to 0 on the very first cell the loops visit.ways[0] - Otherwise, in any column after the first, add
, the count on the left, toways[c - 1] , which still holds the count from above. Column 0 has nothing on its left, so its count carries down unchanged.ways[c] - When every row is done,
holds the number of paths to the bottom-right cell, and the method returns it.ways[n - 1]
The mainshow
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:
[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: 2paths: 1
The grid [1]paths: 0ways[0]ways[0]
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 continueways[c]continue[[0, 0], [1, 0]]
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
keeps one count per column and each row's counts overwrite the row above, so no m × n grid of counts is stored.ways
Picking the cheapest path through a grid of costs, instead of counting the paths, is