Builds onDynamic programming in one dimension
01The idea
Grid DP is dynamic programming where the state is a cell, given by its row and its column. You keep a table the same size as the grid. Each entry holds the answer for reaching that cell, or for the part of the grid up to that cell.
The recurrence comes from the last move. If you can only move right and down, the last move into a cell came from the cell above it or the cell to its left. So the answer for a cell is built from those neighbours. Other move sets give other neighbours, but the idea stays the same.
The fill order matters. Each cell must read only cells that are already filled. When the moves go right, down and diagonally down-right, filling row by row from left to right works, because the cells above and to the left are always done first.
The first row and the first column need care. A cell on the top row has nothing above it. Treat a missing neighbour as 0, or as infinity when you look for a minimum.
The same table idea works for two strings. Then the row is a position in the first string, the column is a position in the second, and each cell compares one character from each.
02How to spot it
Use grid DP when:
- the input is a grid, and you move in fixed directions, such as right and down
- the question asks for the number of paths, or the minimum or maximum cost of a path
- some cells are blocked, or each cell has a cost or a value
- two strings are compared character by character, as in edit distance or the longest common subsequence
If you can move in all four directions, the moves can go in circles, and there is no fill order. That is a graph search problem, not grid DP.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue