DP on Grids

How to solve grid path problems with a two-dimensional DP table, how counting and obstacle variants differ, and what interviewers ask about them.

16 minLesson 3 of 6
On this page
  1. How the table is filled
  2. Code for the cheapest route
  3. Complexity
  4. Variants
  5. Pitfalls
  6. In the interview
  7. What to practise next

A grid DP computes, for every cell of a grid, the best answer for reaching that cell, using the answers already computed for the cells that lead into it. It solves problems such as the cheapest route or the number of routes from one corner to the opposite corner when you may only move right or down. Use it when a problem gives you a grid, restricts the direction of movement, and asks for a minimum, a maximum or a count.

Without a table, you would have to try every route, and the number of routes grows exponentially with the size of the grid: a 20 by 20 grid has more than 35 billion of them. The table avoids this because many routes share the same cells, so the best way to reach a cell only needs to be worked out once.

How the table is filled

The example is a 3 by 4 grid in which each cell has a cost, and you want the cheapest route from the top-left cell to the bottom-right cell, moving only right or down. The route cost is the sum of the costs of all cells on it, including the first and the last.

This is the recipe from Introduction to Dynamic Programming with two indexes. As in 1D Dynamic Programming, you find the recurrence by asking what the last move was.

  1. State. dp[r][c] is the cost of the cheapest route from the start to the cell (r, c), counting both cells.
  2. Recurrence. Every route into (r, c) came from the cell above or the cell to the left, and the cheapest route into (r, c) continues the cheaper of those two: dp[r][c] = min(dp[r − 1][c], dp[r][c − 1]) + cost[r][c].
  3. Base cases. dp[0][0] = cost[0][0]. A cell in the top row can only be entered from the left, and a cell in the left column can only be entered from above.
  4. Order. Fill the table row by row, left to right, so that the cell above and the cell to the left are always filled before they are needed.
  5. Answer. dp[rows − 1][cols − 1].

The recurrence compares whole routes, not single steps. A greedy walk that always steps into the cheaper of the two next cells ends up with a worse route, as the figure shows, because a cheap step can lead into expensive cells.

5 3 1 6 2 9 1 5 6 2 2 9 start end best: 21 greedy: 26
Taking the cheaper next cell each time (dashed) costs 26. The best route (solid) costs 21.
Fill the cheapest-cost tableUse the arrows or ← → keys
for r from 0 to rows - 1:  for c from 0 to cols - 1:    if r == 0 and c == 0: dp[r][c] = cost[0][0]    else if r == 0: dp[r][c] = dp[r][c-1] + cost[r][c]    else if c == 0: dp[r][c] = dp[r-1][c] + cost[r][c]    else: dp[r][c] = min(dp[r-1][c], dp[r][c-1]) + cost[r][c]return dp[rows-1][cols-1]
  1. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 05
    row 1
    row 2
    cost
    5

    1The start cell has no predecessor, so dp[0][0] is its own cost, 5.

  2. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058
    row 1
    row 2
    cost
    3
    left
    5

    2A top-row cell can only be entered from the left, so dp[0][1] is 5 + 3 = 8.

  3. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 0589
    row 1
    row 2
    cost
    1
    left
    8

    3The next top-row cell is 8 + 1 = 9.

  4. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 1
    row 2
    cost
    6
    left
    9

    4The last top-row cell is 9 + 6 = 15.

  5. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17
    row 2
    cost
    2
    up
    5

    5A left-column cell can only be entered from above, so dp[1][0] is 5 + 2 = 7.

  6. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 1716
    row 2
    cost
    9
    up
    8
    left
    7

    6The cell above has 8 and the cell to the left has 7. The left one is smaller, so the result is 7 + 9 = 16.

  7. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 171610
    row 2
    cost
    1
    up
    9
    left
    16

    7The cell above has 9 and the cell to the left has 16. The one above is smaller, so the result is 9 + 1 = 10.

  8. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 2
    cost
    5
    up
    15
    left
    10

    8The cell above has 15 and the cell to the left has 10. The left one is smaller, so the result is 10 + 5 = 15.

  9. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 213
    cost
    6
    up
    7

    9The left-column cell in the last row is 7 + 6 = 13.

  10. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 21315
    cost
    2
    up
    16
    left
    13

    10The cell above has 16 and the cell to the left has 13. The left one is smaller, so the result is 13 + 2 = 15.

  11. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 2131512
    cost
    2
    up
    10
    left
    15

    11The cell above has 10 and the cell to the left has 15. The one above is smaller, so the result is 10 + 2 = 12.

  12. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 213151221
    cost
    9
    up
    15
    left
    12

    12The cell above has 15 and the cell to the left has 12. The left one is smaller, so the result is 12 + 9 = 21.

  13. dp (cheapest cost to reach each cell)
    col 0col 1col 2col 3
    row 058915
    row 17161015
    row 213151221
    answer
    21

    13The answer is 21. Starting at the corner and repeatedly stepping to the smaller of the cell above and the cell to the left gives the marked cells 5, 3, 1, 1, 2, 9, which is the route in the figure.

1 / 13

To recover the route itself, and not just its cost, start at the bottom-right cell and repeatedly move to whichever of the cell above and the cell to the left has the smaller value, as the last step of the tracer does. Reverse the cells you visited to get the route from the start.

Code for the cheapest route

Cheapest route, full table
function fastestRoute(cost) {
  const rows = cost.length;
  const cols = cost[0].length;
  const dp = Array.from({ length: rows }, () => new Array(cols).fill(0));
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (r === 0 && c === 0) dp[r][c] = cost[0][0];
      else if (r === 0) dp[r][c] = dp[r][c - 1] + cost[r][c];
      else if (c === 0) dp[r][c] = dp[r - 1][c] + cost[r][c];
      else dp[r][c] = Math.min(dp[r - 1][c], dp[r][c - 1]) + cost[r][c];
    }
  }
  return dp[rows - 1][cols - 1];
}
 
fastestRoute([[5, 3, 1, 6], [2, 9, 1, 5], [6, 2, 2, 9]]); // 21
def fastest_route(cost):
    rows, cols = len(cost), len(cost[0])
    dp = [[0] * cols for _ in range(rows)]
    for r in range(rows):
        for c in range(cols):
            if r == 0 and c == 0:
                dp[r][c] = cost[0][0]
            elif r == 0:
                dp[r][c] = dp[r][c - 1] + cost[r][c]
            elif c == 0:
                dp[r][c] = dp[r - 1][c] + cost[r][c]
            else:
                dp[r][c] = min(dp[r - 1][c], dp[r][c - 1]) + cost[r][c]
    return dp[rows - 1][cols - 1]
 
fastest_route([[5, 3, 1, 6], [2, 9, 1, 5], [6, 2, 2, 9]])  # 21

Complexity

ApproachTimeSpaceWhy
Try every routeExponentialO(R + C)Each route is R + C − 2 right-or-down moves, so up to about 2R+C routes.
Full tableO(R × C)O(R × C)One cell per grid square, one comparison per cell.
One rowO(R × C)O(C)Each cell only reads the row above, so overwrite one row.

Variants

Counting routes

When the question is how many routes there are, the state becomes ways[r][c], the number of routes from the start to (r, c). Every route arrives from above or from the left and never from both, so the two counts are added instead of compared: ways[r][c] = ways[r − 1][c] + ways[r][c − 1]. The base case is ways[0][0] = 1, and neighbours outside the grid count as 0. In a grid with no obstacles, the answer is also given by a formula: a route has R − 1 moves down and C − 1 moves right in some order, so there are (R + C − 2) choose (R − 1) routes. The table is still needed as soon as there are obstacles.

Obstacles

If some cells are blocked, no route can end on a blocked cell, so its value is 0 for a count. In the table below the cell marked ■ is blocked, and each other cell shows the number of routes that reach it.

col 0col 1col 2col 3
row 01111
row 11■ 012
row 21124

The blocked cell reduces the number of routes from 10 to 4. For a minimum or maximum problem, a blocked cell gets the value infinity (or negative infinity for a maximum) so that no neighbour ever picks it. Watch the start and end cells: if either one is blocked, the answer is 0 or "no route", and the base case must not set ways[0][0] = 1 blindly.

Keeping only one row

Each row of the table reads only itself and the row above, so the table can be replaced by one array of length cols. When you reach column c, ways[c] has not been overwritten yet and still holds the value from the row above, while ways[c − 1] has already been updated for the current row. Adding them is the recurrence, and the result replaces ways[c]. This reduces the memory from O(R × C) to O(C). The cost is that you can no longer recover the route from the table afterwards, so use the full table when the problem asks for the route itself.

Counting routes in O(cols) memory
// grid[r][c] is 1 for a blocked cell, 0 for an open cell.
function countRoutes(grid) {
  const cols = grid[0].length;
  const ways = new Array(cols).fill(0);
  ways[0] = 1;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === 1) ways[c] = 0; // no route ends on a blocked cell
      else if (c > 0) ways[c] += ways[c - 1]; // above + left
    }
  }
  return ways[cols - 1];
}
 
countRoutes([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]); // 4
# grid[r][c] is 1 for a blocked cell, 0 for an open cell.
def count_routes(grid):
    cols = len(grid[0])
    ways = [0] * cols
    ways[0] = 1
    for row in grid:
        for c in range(cols):
            if row[c] == 1:
                ways[c] = 0  # no route ends on a blocked cell
            elif c > 0:
                ways[c] += ways[c - 1]  # above + left
    return ways[cols - 1]
 
count_routes([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]])  # 4

Top-down memoization

The same recurrence can be written as a recursive function best(r, c) that asks for the cheaper of best(r − 1, c) and best(r, c − 1) and caches each result. It has the same time complexity. Its drawbacks are the recursion depth of R + C, which can overflow the stack on a very large grid, and that the one-row space reduction is not possible.

When the technique does not apply

The fill order only works because moves go in one direction, so a cell never depends on a cell that is filled later. If the robot may move up and left as well, a route can loop back to a cell it has already visited, no fill order exists, and the table approach breaks. Cheapest route with free movement in four directions is a shortest-path problem, solved with Dijkstra's algorithm or with breadth-first search when every step costs the same. Diagonal moves are fine as long as they still go forward, because you only add a third neighbour to the recurrence.

Pitfalls

In the interview

The signals are a grid or matrix, movement restricted to right and down (or to a few fixed directions that never go backwards), and a question that asks for the minimum, the maximum or the number of ways to get from one corner to another. Phrases such as "cheapest path", "minimum path sum", "number of unique paths" and "with obstacles" all point to this technique. Say the state and the recurrence out loud before you write any code, because that is what the interviewer is listening for.

"Why not take the cheaper neighbour at each step?" A greedy choice looks only at the next cell and cannot see that a cheap cell may lead into expensive ones. In the figure above it gives 26 instead of 21. The table is correct because each cell holds the best result for the whole route up to that cell.

"What are the time and space complexity, and can you reduce the space?" The time is O(R × C) because each cell is computed once with a constant amount of work. The full table uses O(R × C) memory, and keeping one row reduces it to O(C), or to O(min(R, C)) if you choose the shorter side as the row. You can also write the values into the input grid if you are allowed to modify it, which uses no extra memory.

"How do you return the route and not only its cost?" Keep the full table, then start at the end cell and step back to whichever neighbour has the smaller value (or the larger one, for a maximum), until you reach the start. Reverse the list of cells at the end.

"What changes if some cells are blocked, or the grid is very large?" Blocked cells get 0 for a count and infinity for a minimum. If the answer can be huge, the problem usually asks for it modulo a number, and you take the modulus after each addition.

"What if the robot can move in all four directions?" Then the table fill order breaks, because a cell can depend on a cell that is filled after it. Say that this is a shortest-path problem and use breadth-first search for equal costs or Dijkstra's algorithm for different costs.

Quick check

In the cheapest-route table, dp[1][1] has 8 above it and 7 to its left, and the cell costs 9. What is dp[1][1]?

An open 3 by 3 grid has no blocked cells. How many right-or-down routes go from the top-left cell to the bottom-right cell?

In the one-row version of countRoutes, what does ways[c] hold just before ways[c] += ways[c - 1] runs?

What to practise next

In Knapsack the rows are items and the columns are the remaining capacity, and in DP on Strings they are the positions in two strings, so the same table-filling idea carries over. To practise, try Snowplow to the Road for the cheapest route and Roadworks on the Grid for counting routes around blocked cells.