Command Palette

Search for a command to run...

Module 29

DP on Grids

When the state is a cell: counting paths, cheapest paths, squares of ones, filling in reverse, rolling rows, and two walkers at once.

Intermediate 3 lessons 8 problems ~35 min of lessons

Many DP problems live on a grid where you can only move in some directions, usually right and down. Each cell's answer depends on the cells you could have come from, so you fill the table row by row and read the answer from a corner.

This module covers counting paths (with and without obstacles), minimum-cost paths, triangles and falling paths, the largest square of ones, problems that must be filled backwards from the goal, keeping only one row of memory, and a state with two walkers moving together.

Best after: DP Foundations: 1D

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The basic grid DP, then the one-row version.

  2. Obstacles zero out cells, including along the first row and column.

  3. Cheapest path with min instead of sum of counts.

  4. 29.4TriangleMediumGrid DP

    Bottom-up from the last row makes the answer land in one cell, with O(n) memory.

  5. Three predecessors per cell (diagonals), with boundary checks.

  6. A state that measures a shape: the largest square ending at each cell.

  7. Filling backwards because the requirement depends on what comes later.

  8. Two walkers moving together: the state is (row, column 1, column 2).