Grid DP
Count paths, find the cheapest route, or measure shapes on a 2D grid by giving every cell an answer built from the cells next to it.
Overview
A cell reads its neighbors
In a grid DP the state is a cell. dp[r][c] is the answer for cell (r, c): how many paths reach it, the cheapest way to reach it, or the size of a shape that ends there. When moves go only down and right, a cell can be entered from exactly two cells, the one above and the one to the left. So dp[r][c] is some function of dp[r-1][c] and dp[r][c-1], often together with grid[r][c], the cell's own value, and the problem decides the function. Filling row by row, left to right, makes both neighbors ready in time.
The function is what tells grid problems apart.
- Unique Paths: dp[r][c] is the number of paths into the cell, and the two neighbors add.
- Minimum Path Sum: dp[r][c] is the cheapest total to reach the cell. Take the min of the two neighbors, plus the cell's own cost.
- Maximum path value: dp[r][c] is the best total to reach the cell. Take the max of the two neighbors, plus the cell's own value.
- Count Square Submatrices: dp[r][c] is the side of the largest all-ones square ending here. Take the min of three neighbors, plus 1.
The first row and the first column have only one neighbor, so they are the base cases. A grid of m rows and n columns has mn cells, each costing O(1), so the time is O(mn). A cell reads only the row above and the cell just filled, so one row of length n is enough: O(n) space.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio