Unique Paths

Count the ways a robot can cross a grid from the top-left cell to the bottom-right cell, moving only right or down.

A robot stands in the top-left cell of a grid with m rows and n columns. Each move takes it one cell to the right or one cell down, never left or up. Return the number of different paths that bring it to the bottom-right cell.

Example 1
Input: m = 3, n = 7
Output: 28
Example 2
Input: m = 3, n = 2
Output: 3
Explanation: right-down-down, down-right-down, down-down-right.
Solution

The Idea

Picture a board of squares, like a small chessboard, with a toy robot on the top-left square. Each square of the board is a cell of the grid. The robot can only roll right or down, so every trip ends sooner or later on the bottom-right cell. The question is how many different trips there are.

Example 2 is small enough to list them all. The board has 3 rows and 2 columns, so the robot must go down twice and right once. The one move right can come first, second or last, which gives right-down-down, down-right-down and down-down-right: three paths.

Example 1 has 3 rows and 7 columns, and the answer is 28. Writing out 28 paths by hand is already tiring, and bigger boards have many thousands. So how can we count the paths without listing them?

Think about the robot's very last move. It enters the bottom-right cell either from the cell above it or from the cell to its left. A path that ends with a move down cannot also end with a move right, so the two groups never share a path. The number of paths to the bottom-right cell 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 one. Look at the picture below.

A grid of 3 rows and 7 columns, with the number of paths to each cell. The top row and the left column hold 1. Row 1 reads 1, 2, 3, 4, 5, 6, 7 and row 2 reads 1, 3, 6, 10, 15, 21, 28. The finish holds 28: 7 from above plus 21 from the left.

The grey cells in the top row and the left column all hold 1. The robot reaches a cell in row 0 by rolling straight right, and a cell in column 0 by rolling straight down, with no other choice. Every other cell adds the cell above it to the cell on its left. In row 1, column 1 gets 1 + 1 = 2, column 2 gets 1 + 2 = 3, and so on up to 7.

Now look at the finish, in row 2 and column 6. The cell above it, marked "from above: 7 paths", holds 7. The cell on its left, marked "from the left: 21 paths", holds 21. Together they make 28, the answer to Example 1.

So no path is ever walked. Each cell's count is built from two counts already written into the grid, row by row from the top. Building the count for the finish out of the counts of the cells before it, as this grid does, is called dynamic programming.

Solution Approach

Turning the grid of counts into code means settling three things: why walking every path is too slow, what each cell of the table stands for, and how to keep only one row of it. There is also a formula that gives the count directly, as an optional extra.

Walking every path

Why not let a program try every path, moving right or down from each cell, and count the ones that reach the finish? It gives the right answer, but it has to arrive at the finish once for each path. A 10 by 10 grid has 48,620 paths, and each one is 18 moves long, so the work grows as fast as the answer does.

What one cell of the table means

Which number goes into the cell in row i and column j? It is the number of paths from the start to that cell. The top row and the left column hold 1. Every other cell holds the count in the cell above it plus the count in the cell on its left. Calling that count paths(i, j), the rule reads paths(i, j) = paths(i - 1, j) + paths(i, j - 1).

Filling row by row from the top, and each row from left to right, means both of those counts are ready when a cell needs them. The last cell filled is the finish.

Keeping one row instead of the whole grid

Does the program need all m rows at once? A new row only reads the row just above it, so one array of n counts, called dp, is enough. For Example 1, before row 1 starts, dp holds row 0 of the picture: seven 1s.

To fill the cell in column j of the next row, the code adds dp[j - 1] to dp[j]. At that moment dp[j] still holds the old value, the count from the cell above. Its neighbour dp[j - 1] was just updated, so it already holds the count from the cell on the left. In the picture, the last step of row 2 adds 21 to 7, and dp[6] becomes 28.

A formula for the count (optional)

Every path in Example 1 is 8 moves long: 2 moves down and 6 moves right, in some order. A path is fixed by choosing which 2 of the 8 moves go down, and there are 28 ways to choose them. In general the answer is (m + n - 2)! / ((m - 1)! × (n - 1)!), where k! means 1 × 2 × ... × k.

The formula is correct, but computing the factorials in Java int breaks early. The factorial 13! is 6,227,020,800, more than an int can store, so the product wraps around to the wrong value 1,932,053,504. For a 10 by 10 grid, 18! / (9! × 9!) worked out in int comes out as 0 instead of 48,620. The table never holds a count bigger than the answer, so it stays correct whenever the answer itself fits in an int.

Java Solution

The method uniquePaths works in these steps:

  1. First, create the array dp with new int[n], one count per column. It holds one row of the grid at a time.
  2. Fill it with 1 using Arrays.fill(dp, 1). That is the top row, where each cell has one path.
  3. Go through the remaining rows with a loop that moves i from 1 to m - 1. Inside it, a second loop moves j from 1 to n - 1 and runs dp[j] += dp[j - 1], adding the count on the left to the count from above. The second loop starts at column 1, so dp[0] stays 1 for the left column.
  4. After the last row, dp[n - 1] holds the count for the bottom-right cell, and the method returns it.

The main method runs both examples, a grid of a single cell, a grid of one row, a grid of one column, and a 10 by 10 grid.

Java
import java.util.Arrays;

public class UniquePaths {

    public static int uniquePaths(int m, int n) {
        int[] dp = new int[n];           // dp[j]: paths to column j of the current row
        Arrays.fill(dp, 1);              // the top row: one way to each cell
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] += dp[j - 1];      // from above (old dp[j]) plus from the left
            }
        }
        return dp[n - 1];
    }

    public static void main(String[] args) {
        System.out.println("3 x 7: " + uniquePaths(3, 7));
        System.out.println("3 x 2: " + uniquePaths(3, 2));
        System.out.println("1 x 1: " + uniquePaths(1, 1));
        System.out.println("1 x 5: " + uniquePaths(1, 5));
        System.out.println("5 x 1: " + uniquePaths(5, 1));
        System.out.println("10 x 10: " + uniquePaths(10, 10));
    }
}

Running it prints:

Output
3 x 7: 28
3 x 2: 3
1 x 1: 1
1 x 5: 1
5 x 1: 1
10 x 10: 48620

The line 3 x 7: 28 is the finish cell from the picture, and 3 x 2: 3 matches the three paths listed for Example 2. For 1 x 1: 1, the robot already stands on the finish, and neither loop runs, so the method returns the 1 from the fill.

The lines 1 x 5: 1 and 5 x 1: 1 show the two edges. With one row, the loop over i never starts and the answer is the top row's 1. With one column, the second loop, over j, never starts, so dp[0] keeps its 1. The last line, 10 x 10: 48620, is the count that the int factorial formula turned into 0.

Complexity

The work is one addition for every cell outside the top row and the left column.

  • Time: O(m × n), because the two loops visit each of the (m - 1) × (n - 1) inner cells once, with one addition each, after the fill of n counts for the top row.
  • Space: O(n), because dp keeps only one row of n counts, and each new row is written over the row above it.

When some cells are blocked and the robot must go around them, the same table still works with one change: see Unique Paths II.