Longest Increasing Path in a Matrix
Find the maximum length of a four-directional path whose values strictly increase.
Open on LeetCode ↗Intuition
Starting a raw DFS from every cell repeats the same suffix paths exponentially. Strictly increasing moves can never form a cycle because values must rise at every step. That turns the matrix into an implicit DAG, and the best path beginning at a cell depends only on larger neighbors. Memoizing that value solves each cell once.
When moves must strictly increase or decrease, the values themselves impose a DAG even if the grid has undirected adjacency. Memoized DFS is a compact way to compute longest paths in that implicit DAG.
Approach
Define a reusable path length for each cell
Let dfs(row, col) return the longest increasing path that starts at that cell, counting the cell itself. Initialize its answer to one because stopping immediately is always valid.
Extend only to strictly larger neighbors
Inspect the four adjacent positions and recurse when the neighbor is in bounds and has a greater value. Take one plus the largest returned suffix length.
Memoize every starting cell
Cache DFS results so overlapping searches reuse completed suffixes. Evaluate every cell as a possible beginning and return the maximum cached path length.
Solution
Common pitfalls
Allowing equal-valued moves
matrix[nr][nc] >= matrix[row][col]
matrix[nr][nc] > matrix[row][col]
The path must be strictly increasing.
Forgetting to count the current cell
best = 0
best = 1
A cell with no larger neighbor still forms a length-one path.
Using one global visited set
if (row, col) in visited:
return 0@cache def dfs(row, col):
Cells may belong to many candidate paths; their optimal suffix should be reused, not forbidden.
Edge cases
The cell alone forms a path of length one.
Strict comparison permits no move, so every cached length is one.
Four-directional DFS explores turns without imposing row or column order.