matrix
graph
dynamic-programming
breadth-first-search
Given an m x n integer matrix, you may start from any cell and move up, down, left, or right. You may only move to a cell with a strictly larger value. Return the length of the longest valid path.
Input / output
- Input:
matrix: int[][] - Output: length of the longest strictly increasing path
Examples
matrix = [[9,9,4],[6,6,8],[2,1,1]]returns4from the path1 -> 2 -> 6 -> 9.matrix = [[3,4,5],[3,2,6],[2,2,1]]returns4from the path3 -> 4 -> 5 -> 6.matrix = [[1]]returns1.
Constraints
1 <= m, n <= 200-2^31 <= matrix[r][c] <= 2^31 - 1
Target complexity
- Aim for
O(m * n)orO(m * n + edges)time, not exponential search.
Hints
- If you treat each cell as a graph node with directed edges to larger neighbors, the graph is acyclic.
- Local peaks have outdegree
0. Repeatedly peel one topological layer at a time, or memoize DFS results per cell.
Follow-up Why does allowing diagonal moves change only the neighbor count, not the core DAG reasoning?
Examples
Example 1
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Example 2
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Example 3
Input: matrix = [[1]]
Output: 1
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.