329. Longest Increasing Path in a Matrix
Hard NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- 2-D Dynamic Programming
- Time
- O(m * n)
- Space
- O(m * n)
Standard Solution (C++)
SummaryFind the length of the longest strictly increasing path in a grid, moving only up, down, left, or right.
Approach
Key idea: From each cell the longest increasing path is fixed, so memoize it. Because moves go strictly up in value the dependency graph is acyclic, so DFS with caching is safe.
Steps:
- For each cell run a DFS that explores neighbors with strictly larger values.
- The result for a cell is 1 plus the max over valid neighbors; cache it in a memo grid.
- Track the global maximum over all starting cells.
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> memo(m, vector<int>(n, 0));
int best = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
best = max(best, dfs(matrix, memo, i, j));
return best;
}
private:
int dfs(vector<vector<int>>& matrix, vector<vector<int>>& memo, int i, int j) {
if (memo[i][j] != 0) return memo[i][j];
int m = matrix.size(), n = matrix[0].size();
int dirs[5] = {0, 1, 0, -1, 0};
int best = 1;
for (int d = 0; d < 4; ++d) {
int ni = i + dirs[d], nj = j + dirs[d + 1];
if (ni >= 0 && ni < m && nj >= 0 && nj < n && matrix[ni][nj] > matrix[i][j]) {
best = max(best, 1 + dfs(matrix, memo, ni, nj));
}
}
memo[i][j] = best;
return best;
}
}; Time O(m * n) Space O(m * n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.