Longest Increasing Path in a Matrix - Problem
Given an m × n matrix of integers, find the length of the longest strictly increasing path. You can move in four directions (up, down, left, right) but cannot move diagonally or outside the matrix boundaries.
Think of it like hiking through a terrain where each cell represents an elevation. You want to find the longest uphill path where each step takes you to a higher elevation than the previous one.
Example: In matrix [[9,9,4],[6,6,8],[2,1,1]], one longest increasing path could be 1 → 2 → 6 → 9 with length 4.
Input & Output
example_1.py — Basic Matrix
$
Input:
matrix = [[9,9,4],[6,6,8],[2,1,1]]
›
Output:
4
💡 Note:
The longest increasing path is [1,2,6,9] with length 4. Starting from bottom-left (1), we can go up to 2, then up to 6, then right to 9.
example_2.py — Complex Path
$
Input:
matrix = [[3,4,5],[3,2,6],[2,2,1]]
›
Output:
4
💡 Note:
The longest increasing path is [2,3,4,5] or [2,3,4,6] both with length 4. Multiple paths can have the same maximum length.
example_3.py — Single Element
$
Input:
matrix = [[1]]
›
Output:
1
💡 Note:
With only one element, the longest increasing path has length 1 (the element itself).
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 200
- -231 ≤ matrix[i][j] ≤ 231 - 1
- Note: Matrix values can be negative
Visualization
Tap to expand
Understanding the Visualization
1
Survey the terrain
Look at the elevation map (matrix) and identify all possible starting points
2
Use smart exploration
From each point, explore all uphill directions but remember the best path from each visited location
3
Cache your findings
Once you find the longest uphill path from a location, mark it on your map so you don't need to re-explore
4
Find the maximum
Compare all starting points and return the longest trail length found
Key Takeaway
🎯 Key Insight: Memoization transforms this from an exponential search problem into a linear one by ensuring each location is fully explored exactly once.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code