Sub topic 15
Longest Increasing Path: Memoized DFS over a DAG
This chapter assumes you are comfortable with recursion, Python's functools.lru_cache, and the earlier chapters on fill order and top-down memoization.
When Row-by-Row Filling Breaks Down
In every grid problem so far, moves went only right and down. That meant a single fixed fill order (top to bottom, left to right) always computed a cell's dependencies before the cell itself.
Now allow moves in all four directions. The task is to find the length of the longest path through a matrix where each step goes to an adjacent cell holding a strictly larger value. A cell can depend on the cell above it, below it, or beside it, so no row or column order works for every input.
The State and the Recurrence
Let dfs(i, j) be the length of the longest strictly increasing path that starts at cell (i, j).
- Base value: a cell with no larger neighbor gives a path of length 1, the cell alone.
- Transition:
dfs(i, j) = 1 + max(dfs(x, y))over the in-bounds neighbors(x, y)withmatrix[x][y] > matrix[i][j].
The answer is the maximum of dfs(i, j) over all cells, because the path can start anywhere.
Why Memoization Is Safe Here
The strictly-increasing rule is what makes this work. Draw an edge from each cell to every larger neighbor. Each edge goes from a smaller value to a larger one, so following edges can never bring you back to a cell you already visited. The graph is a directed acyclic graph (DAG). Every DAG has a valid evaluation order, called a topological order. Memoized recursion finds that order for you without you writing it down.
from functools import lru_cache
def longest_increasing_path(matrix):
m, n = len(matrix), len(matrix[0])
@lru_cache(maxsize=None)
def dfs(i, j):
best = 1
for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
x, y = i + di, j + dj
if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]:
best = max(best, 1 + dfs(x, y))
return best
return max(dfs(i, j) for i in range(m) for j in range(n))
print(longest_increasing_path([[9, 9, 4], [6, 6, 8], [2, 1, 1]])) # 4The cache lives inside the outer function, so each call gets a fresh cache and results from one matrix never leak into the next.
Cost
Each cell is computed once, and each computation checks four neighbors. That gives O(mn) time. The cache uses O(mn) space, and in the worst case the recursion stack is O(mn) deep as well.
Common Errors
| Mistake | Effect |
|---|---|
| Using `>=` instead of `>` | Equal neighbors create cycles, and the recursion never ends |
| Adding a `visited` set | Not needed, because a DAG has no cycles; it also corrupts cached values |
| Returning only `dfs(0, 0)` | Misses paths that start somewhere other than the top-left cell |
Exercise
What does longestincreasingpath return for [[3, 4, 5], [3, 2, 6], [2, 2, 1]], and which path produces it?
Show answer
It returns 4. One such path is 3 → 4 → 5 → 6, starting at (0, 0), moving right twice, then down to (1, 2). Another is 2 at (1, 1) → 4 → 5 → 6. No path of length 5 exists.
Exercise
Suppose the rule changes to allow steps to equal or larger values. Why does the memoized DFS above stop being correct?
Show answer
Two adjacent equal cells would each depend on the other, so the graph has a cycle and is no longer a DAG. dfs would recurse between them forever, or return wrong values if you guarded it with a visited set. The problem then needs a different method, such as collapsing groups of equal cells first.