Algo-Sim › Dynamic Programming

Unique Paths

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Count right/down paths across a grid: each cell is the sum of the cell above and the cell to its left.

Problem

A robot starts in the top-left cell of an m × n grid and can only move right or down. Return how many different paths take it to the bottom-right cell.

Constraints

Edge cases to test

Follow-up questions

Is there a closed form?
C(m + n − 2, m − 1): choose which of the moves go down. Compute it step by step to avoid overflow.
How much space is needed?
One row: row[j] += row[j − 1], O(n).

Solution

Java

public int uniquePaths(int m, int n) {
    int[][] dp = new int[m][n];
    for (int r = 0; r < m; r++) dp[r][0] = 1;
    for (int c = 0; c < n; c++) dp[0][c] = 1;
    for (int r = 1; r < m; r++) {
        for (int c = 1; c < n; c++) {
            dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
        }
    }
    return dp[m - 1][n - 1];
}

Python

def unique_paths(m, n):
    dp = [[0] * n for _ in range(m)]
    for r in range(m):
        dp[r][0] = 1
    for c in range(n):
        dp[0][c] = 1
    for r in range(1, m):
        for c in range(1, n):
            dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
    return dp[m - 1][n - 1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> dp = vector<vector<int>>(m, vector<int>(n));
        for (int r = 0; r < m; r++)
            dp[r][0] = 1;
        for (int c = 0; c < n; c++)
            dp[0][c] = 1;
        for (int r = 1; r < m; r++) {
            for (int c = 1; c < n; c++) {
                dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
            }
        }
        return dp[m - 1][n - 1];
    }
};

More Dynamic Programming problems