AlgoFrames

Grid DP: paths, minimum path sum, obstacles

Grid DP computes each cell from the cells above and to the left, counting paths or finding the cheapest path around obstacles.

Before you start: Longest increasing subsequence; the n log n version.

Counting grid paths around obstacles

The idea

A robot walks from the top-left to the bottom-right, only right or down. How many different routes are there?

Listing routes one by one gets slow fast: a 10 × 10 grid already has 48,620 of them. Counting them needs a smarter idea.

Intuition

A cell on the top row can only be reached from its left. So every top-row and left-column cell has exactly 1 path.

The last move into a cell came from above or from the left. So its count is the count above plus the count to the left.

Every route into (1, 3) ends with one move, down from (0, 3) or right from (1, 2). The two groups never overlap, so their sizes add.

Complexity

The grid fills rows × cols cells with O(1) work each, so it runs in O(rows · cols). Listing every route grows exponentially.

The y axis is logarithmic. An n × n grid has C(2n − 2, n − 1) routes, about 4ⁿ, but only n² cells.

Each row reads only the row above it. One array of length cols, updated in place, is enough: O(cols) space.

Before the update, row[c] still holds the value from the row above. Adding row[c − 1], the new left neighbour, gives the new count.

Pitfalls

An obstacle on the top row blocks every cell after it. Filling the whole edge with 1 counts routes that do not exist.

If the start or the goal is an obstacle, the answer is 0. Set dp[0][0] from the grid, not to a fixed 1.

Variations

Minimum path sum uses the same top-and-left rule with min instead of +. The next lesson builds it.

String DP such as longest common subsequence fills the same kind of table, one string along each side.

Minimum path sum and drawing the path

The idea

Every cell has a cost. Walking right or down from start to goal, which route has the smallest total?

Intuition

A new grid: stepping to the cheaper neighbour each time fails. The greedy walk pays 13; the best path pays 9.

A cheap cell can lead into an expensive region. The choice at each step depends on what lies further on, so we need totals, not local costs.

Back to the first grid. The cheapest route into a cell comes from the cheaper of its top and left totals, plus its own cost.

Any route into (1, 1) enters from (0, 1) or (1, 0). The best such route uses the best route into that neighbour, so best(1, 1) = 5 + min(4, 2).

Complexity

Each cell is filled once from two neighbours: O(rows · cols) time. Trying every route would be exponential.

Only the row above is ever read, so one row of totals is enough: O(cols) extra space. Drawing the path needs the full table.

Walking back from the goal compares the totals above and to the left at every step. With a single row those older totals are overwritten.

Pitfalls

Edge cells need running sums. Copying the cell's own cost forgets everything paid before it.

Treating cells outside the grid as 0 makes min pick a route from nowhere. Use infinity, or fill the edges first.

For counting, an outside 0 adds nothing and is harmless. For a minimum, 0 is the best possible value, so it wins every comparison.

Variations

Triangle: each cell reads the two cells above it instead of top and left. The answer is the smallest total in the last row.

Dungeon game fills the table backwards from the goal. Each cell needs the bottom and right cells, not top and left.

Code

Pseudocode

paths(grid):
  dp ← rows × cols table of 0
  dp[0][0] ← 1 if grid[0][0] is open else 0
  for c ← 1 to cols - 1: dp[0][c] ← 0 if wall else dp[0][c - 1]
  for r ← 1 to rows - 1: dp[r][0] ← 0 if wall else dp[r - 1][0]
  for r ← 1 to rows - 1
    for c ← 1 to cols - 1
      if grid[r][c] is a wall: dp[r][c] ← 0
      else: dp[r][c] ← dp[r - 1][c] + dp[r][c - 1]
  return dp[rows - 1][cols - 1]

Python

def unique_paths(grid):
    rows, cols = len(grid), len(grid[0])
    dp = [[0] * cols for _ in range(rows)]
    dp[0][0] = 1 if grid[0][0] == 0 else 0
    for c in range(1, cols):
        dp[0][c] = 0 if grid[0][c] == 1 else dp[0][c - 1]
    for r in range(1, rows):
        dp[r][0] = 0 if grid[r][0] == 1 else dp[r - 1][0]
    for r in range(1, rows):
        for c in range(1, cols):
            if grid[r][c] == 1:
                dp[r][c] = 0
            else:
                dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
    return dp[rows - 1][cols - 1]

JavaScript

function uniquePaths(grid) {
  const rows = grid.length, cols = grid[0].length;
  const dp = Array.from({ length: rows }, () => new Array(cols).fill(0));
  dp[0][0] = grid[0][0] === 0 ? 1 : 0;
  for (let c = 1; c < cols; c++) dp[0][c] = grid[0][c] === 1 ? 0 : dp[0][c - 1];
  for (let r = 1; r < rows; r++) dp[r][0] = grid[r][0] === 1 ? 0 : dp[r - 1][0];
  for (let r = 1; r < rows; r++) {
    for (let c = 1; c < cols; c++) {
      if (grid[r][c] === 1) dp[r][c] = 0;
      else dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
    }
  }
  return dp[rows - 1][cols - 1];
}

Java

static long uniquePaths(int[][] grid) {
    int rows = grid.length, cols = grid[0].length;
    long[][] dp = new long[rows][cols];
    dp[0][0] = grid[0][0] == 0 ? 1 : 0;
    for (int c = 1; c < cols; c++) dp[0][c] = grid[0][c] == 1 ? 0 : dp[0][c - 1];
    for (int r = 1; r < rows; r++) dp[r][0] = grid[r][0] == 1 ? 0 : dp[r - 1][0];
    for (int r = 1; r < rows; r++) {
        for (int c = 1; c < cols; c++) {
            if (grid[r][c] == 1) dp[r][c] = 0;
            else dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
        }
    }
    return dp[rows - 1][cols - 1];
}

Practice problems (6)

Unique paths Warm-up

A robot sits in the top-left cell of an m × n grid. It moves only right or down and wants to reach the bottom-right cell.

Return the number of different paths.

Fill the paths table Warm-up

Follow the path-counting table on a 3 × 3 grid with an obstacle at (1, 0). Answer each question before the step plays.

Minimum path sum Standard

grid holds non-negative costs. Start in the top-left cell, move only right or down, and finish in the bottom-right cell. The cost of a path is the sum of every cell on it, both ends included.

Return the smallest possible cost.

Unique paths II Standard

A robot starts in the top-left cell of obstacleGrid and moves only right or down to the bottom-right cell. Cells holding 1 are obstacles the robot cannot enter; cells holding 0 are open.

Return the number of different paths.

Triangle Standard

triangle has one number in row 0, two in row 1, and so on. Start at the top. From index i in one row you may step to index i or i + 1 in the next row.

Return the smallest sum of a path from the top to any cell in the bottom row.

Dungeon game Challenge

A knight starts in the top-left room of dungeon and must reach the princess in the bottom-right room, moving only right or down. Entering a room changes the knight's health by its value: negative values hurt, positive values heal. The start and end rooms count too.

If health ever drops to 0 or below, the knight dies. Return the smallest starting health that lets the knight reach the princess.

Related topics

Next on the path: String DP: LCS, edit distance, palindromic subsequence