Sub topic 15
Longest Increasing Path: Memoized DFS over a DAG
Every grid so far allowed moves in only some directions, such as right and down. Those limits gave you a simple fill order: go row by row and column by column, and each cell's dependencies are already computed when you reach it. This chapter removes the limit. Moves can go up, down, left, or right. The question is whether DP still works.
This chapter assumes you have read the earlier chapters on defining a state, writing recurrences, fill order, and top-down memoization versus bottom-up tabulation. It also assumes you know recursion and Big-O notation.
The Problem
You are given an m x n matrix of integers. A path moves between cells that share an edge, in any of the four directions. Each step must go to a strictly larger value. Find the length of the longest such path, counted in cells.
For this matrix:
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 9 | 9 | 4 |
| row 1 | 6 | 6 | 8 |
| row 2 | 2 | 1 | 1 |
The answer is 4, using the path 1 → 2 → 6 → 9. The cells are (2,1) → (2,0) → (1,0) → (0,0).
Why Row-by-Row Filling Fails
Suppose you try a table dp[i][j] and fill it top to bottom. Cell (1,0) holds 6, and it can step up to the 9 at (0,0). That dependency is already computed. Cell (2,1) holds 1, and it can step up to (1,1), which is fine, and left to (2,0), which is also fine. Now look at (0,2), which holds 4. It can step down to the 8 at (1,2), and that cell sits in a row you have not filled yet.
A cell's dependencies can lie in any direction, so no fixed scan order is guaranteed to work. The dependency order comes from the values in the matrix, not from the positions.
The State and the Recurrence
Define the state as follows:
dfs(i, j)is the length of the longest strictly increasing path that starts at cell(i, j).
From (i, j), the path either stops, giving length 1, or steps to a neighbor with a larger value and continues from there:
dfs(i, j) = 1 + max(dfs(x, y))over the in-bounds neighbors(x, y)withmatrix[x][y] > matrix[i][j], or1if no such neighbor exists.
The answer is the maximum of dfs(i, j) over all cells, because the longest path can start anywhere.
Why This Is Safe: The Dependency Graph Is a DAG
Draw an edge from each cell to every neighbor with a larger value. Values strictly increase along every edge, so following edges can never bring you back to a cell you already visited. A cycle would need some value to be greater than itself. The graph is therefore a directed acyclic graph (DAG).
This matters for two reasons:
- The recursion terminates. Every call moves to a strictly larger value, and there are finitely many values.
- Memoization is valid. The best path from
(i, j)does not depend on how you arrived there. Any cell already on the path has a smaller value, so the rest of the path could never reach it anyway. You don't need to track a "visited" set, so the state is just(i, j).
The general longest simple path problem on a graph with cycles is NP-hard. The strict-increase rule turns it into a longest path on a DAG, which takes linear time.
Equal neighbors, such as the two 6s or the two 1s, have no edge between them. That is why the problem says "strictly".
Top-Down: Memoized DFS
Memoization fits naturally here. You never choose an order. The recursion finds the dependencies itself, and the cache makes sure each cell is solved only once.
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]])) # 4After the run, the cache holds these values:
| Row | col 0 | col 1 | col 2 |
|---|---|---|---|
| row 0 | 1 | 1 | 2 |
| row 1 | 2 | 2 | 1 |
| row 2 | 3 | 4 | 2 |
Every 9 and the 8 are local maxima, so each scores 1. The 1 at (2,1) reaches 4 by going through the 2.
The bounds check 0 <= x < m and 0 <= y < n handles the boundaries, so you need no padding. The cache is created fresh inside each call to longest_increasing_path, so separate matrices never share stale results.
Bottom-Up: Process Cells in Value Order
The DAG gives you a fill order, but it is a topological order and not a positional one. If you process cells from the largest value to the smallest, every larger neighbor is finished before you need it.
def longest_increasing_path_sorted(matrix):
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
cells = sorted(
((matrix[i][j], i, j) for i in range(m) for j in range(n)),
reverse=True,
)
dp = [[1] * n for _ in range(m)]
for value, i, j in cells:
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] > value:
dp[i][j] = max(dp[i][j], 1 + dp[x][y])
return max(max(row) for row in dp)
print(longest_increasing_path_sorted([[9, 9, 4], [6, 6, 8], [2, 1, 1]])) # 4Ties in the sort order don't matter. Cells with equal values never depend on each other, so you can process them in any order.
A third option avoids sorting. Kahn's algorithm peels the DAG layer by layer: start with cells that have no larger neighbor, remove them, and count how many layers you remove. The layer count is the answer, and the whole run takes O(mn).
Complexity
Each cell is computed once and looks at four neighbors.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Memoized DFS | O(mn) | O(mn) cache + O(mn) call stack | Simplest to write |
| Sort by value | O(mn log mn) | O(mn) | No recursion |
| Kahn's layer peeling | O(mn) | O(mn) queue and out-degree counts | No recursion, no sort |
You cannot use the rolling-array trick from earlier chapters here. A cell's dependencies can be anywhere in the grid, so you have to keep the whole table.
Failure Modes and Gotchas
Recursion depth
The call stack can grow as deep as the longest path, and that path can be up to m * n cells long. Picture a 200 x 200 grid whose values snake upward, increasing along every row and turning at each end. Its longest path visits all 40,000 cells. CPython's default recursion limit is 1000, and lru_cache wrappers make each level more expensive. The memoized version raises RecursionError on inputs like that.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Using `>=` instead of `>` | Equal neighbors form a 2-cycle, so the recursion never ends | Keep the comparison strict |
| Adding a per-path `visited` set | The result now depends on history, so the cache returns wrong answers | Drop it. Strict increase already prevents revisits |
| Starting only from `(0, 0)` | Misses paths that start elsewhere | Take the max over all cells |
| Calling `matrix[0]` on an empty input | `IndexError` | Guard for an empty matrix first |
| Defining the state as "longest path ending at" but recursing to larger neighbors | The direction is mixed up, giving wrong lengths | Pick one direction and recurse toward its predecessors |
When this pattern applies
Use memoized DFS over a grid when the allowed moves make the dependency graph acyclic, but no simple scan order follows from the positions. Look for a quantity that strictly changes on every move, such as a value, a remaining budget, or a step count. If moves can cycle, for example on equal values or when going back is allowed, plain DP fails. You then need either a larger state that breaks the cycle or a shortest-path algorithm such as BFS or Dijkstra.
Exercise
The problem changes to allow all eight moves, including diagonals, with the same strictly-increasing rule. Does memoized DFS still work, and what is the new time complexity?
Show answer
Yes. Every move still goes to a strictly larger value, so the dependency graph is still a DAG and caching by (i, j) is still valid. Add the four diagonal offsets to the direction list. Each cell now checks 8 neighbors, so the time is O(8mn), which is still O(mn).
Exercise
A teammate changes the comparison to matrix[x][y] >= matrix[i][j] to allow flat steps. What happens on the example matrix, and why?
Show answer
The two adjacent 6s, and likewise the two adjacent 1s, now point at each other. That creates a cycle: dfs(1,0) calls dfs(1,1), which calls dfs(1,0) again before either has returned and been cached. The recursion never ends and raises RecursionError. Allowing flat steps breaks the DAG property that the whole approach depends on.
Exercise
Write the recurrence for counting all strictly increasing paths in the grid, where a single cell counts as a path, instead of finding the longest one.
Show answer
Let count(i, j) be the number of increasing paths that start at (i, j). Then count(i, j) = 1 + the sum of count(x, y) over the neighbors with matrix[x][y] > matrix[i][j]. The answer is the sum of count(i, j) over all cells, usually taken modulo a large prime. The DAG argument is the same, so the same memoized DFS or sorted-order fill works with max replaced by sum.