Learn / Dynamic programming

2D grid DP

In grid DP the state is a cell (row, column): the best or the count of ways to reach it, built from the cells you can arrive from. Fill row by row so those cells are ready. Many 'best rectangle' questions fix two rows and reduce the rest to a 1D problem on column sums.

How to recognise it

  • Moving through a grid with only some directions allowed.
  • Counting paths, or the cheapest or most valuable path.
  • The best square or rectangle of a matrix.

Cell by cell

for r in rows:
    for c in columns:
        dp[r][c] = cell value combined with dp of the cells you arrive from
ProblemArrive from
unique pathsup, left
min cost pathup, left, diagonal
falling path, gold minethe three neighbours in the previous row (or column)
trianglethe two below (fill bottom up)
cherry pickup IIstate is (row, column of robot 1, column of robot 2)

Rectangles

Fix a top and bottom row (or left and right column); add up each column between them. Now the question is about a 1D array: the best subarray (Kadane), or the longest subarray with sum 0 (prefix sums in a hash map).

Common mistakes

  • Overwriting values in one-row tables in the wrong order.
  • Forgetting cells blocked by obstacles in the first row and column.

Problems

0 of 14 solved

Check yourself

Unique paths in a 3 × 3 grid moving right and down?

For a falling path, each cell comes from which cells?

Largest all-1 square ending at a cell: what limits it?

For the maximum-sum rectangle, what happens after fixing the left and right columns?