Longest Increasing Path in a Matrix
Longest Increasing Path in a Matrix is LeetCode 329 (Hard). Given an m × n grid of integers, return the length of the longest path in which every step moves up, down, left or right to a cell with a strictly larger value.
Diagonal moves are not allowed, the path may not leave the grid, and its length counts cells, so a single cell is a path of length 1.
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 200
- 0 <= matrix[i][j] <= 2³¹ - 1
Intuition
Let dfs(r, c) be the longest climbing path that starts at cell (r, c). It is 1 plus the best dfs among the larger neighbours, or just 1 if no neighbour is larger.
The key fact is that a strictly increasing path can never return to a cell: getting back would need a step down. So the grid has no cycles, every dfs(r, c) has one fixed answer, and that answer can be cached the first time it is computed. With the cache, each of the m·n cells is solved once, instead of once for every path that passes through it.
Approach
Two ways to find the longest climb
Ask each cell for the longest climb starting there and remember the answer.
- Short: one small recursive function.
- Direct: the rule reads like the problem statement.
The usual interview answer; mind the recursion depth on snake-shaped grids.
Treat each climb as an edge and remove cells with no larger neighbour, layer by layer.
- No recursion: safe for any grid shape.
- Topological sort: the same Kahn's algorithm used on course schedules.
The number of layers removed is the answer.
Both visit each cell and each neighbour pair a constant number of times. The cached DFS is traced below; the layer-peeling BFS follows the demo.
Write the recursive rule
dfs(r, c) starts at best = 1 for the cell itself. For each of the four neighbours that is inside the grid and holds a larger value, set best = max(best, 1 + dfs(neighbour)).
Cache every finished cell
Store dfs(r, c) the first time it returns and reuse it on every later call. The value cannot depend on how you reached the cell, because the path ahead only moves to larger values, never back to where you came from.
Try every cell as the start
The longest path can begin anywhere, so call dfs on every cell and return the largest result. Most of those calls hit the cache, so this loop adds almost no work.
Watch the recursion depth
A grid whose values climb in one long snake makes the recursion as deep as the number of cells, up to 40,000. In Python raise the limit with sys.setrecursionlimit, or use the layer-peeling BFS shown below, which has no recursion at all.
Code in Python, C++ and Java
Peel layers with BFS
Count, for every cell, how many neighbours are larger. Cells with a count of 0 are peaks: no path can continue from them, so they form the first layer. Remove a layer, lower the counts of the smaller neighbours of its cells, and any cell whose count drops to 0 joins the next layer. The longest path visits one cell per layer, so the number of layers is the answer.
Common pitfalls
Allowing equal neighbours
if matrix[nr][nc] >= matrix[r][c]:
if matrix[nr][nc] > matrix[r][c]:
The path must strictly increase. Worse, with >= two equal neighbours call each other back and forth: on [[7, 7]] the recursion overflows the stack instead of returning 1.
Adding a visited set
if (r, c) in visited:
return 0@cache def dfs(r, c):
Strict climbing already prevents revisits, so a visited set adds nothing. A global one is wrong: a cell finished on one path is then treated as blocked for the next, and [[1, 2], [4, 3]] returns less than 4.
Running DFS without the cache
def dfs(r, c): # no @cache
@cache def dfs(r, c):
The answer stays correct, but every path recomputes everything below it. A 200 × 200 grid where values grow towards one corner has an exponential number of climbing paths and times out.
Edge cases
[[7, 7], [7, 7]]No move is allowed, so every cell scores 1 and the answer is 1.
Complexity
Longest Increasing Path in a Matrix FAQ
Why does caching work here when it fails for longest paths in general graphs?
In a graph with cycles, the best path from a node depends on which nodes the path has already used, so one cached number per node is not enough. Here a climbing path can never reach a used cell again, because that would need a step down. The grid is a directed acyclic graph, and in such a graph the longest path from a node is a fixed value.
Can I start the search only from the smallest cells?
Yes. A longest path can always be extended backwards until it starts at a cell with no smaller neighbour, so starting from those cells is enough. With the cache it saves little, because calls on other cells are cheap cache hits anyway.