Longest Increasing Path in a Matrix

Longest strictly-increasing path in any direction — DFS with memoization.

Hard
Time O(m * n) Space O(m * n)
LeetCode
5 min read
dp memoization grid

Problem#

Length of the longest strictly-increasing path in the matrix, moving up/down/left/right.

Examples#

  • [[9,9,4],[6,6,8],[2,1,1]]4

Constraints#

  • 1 <= m, n <= 200.

Approach#

DFS with memoization on (r, c). Each call returns 1 + max DFS over neighbors with strictly greater value. Since values strictly increase, no cycles → memo always safe.

Solution#

Longest Increasing Path
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> memo(m, vector<int>(n, 0));
function<int(int,int)> dfs = [&](int r, int c) {
if (memo[r][c]) return memo[r][c];
int best = 1;
int dr[4] = {1,-1,0,0}, dc[4] = {0,0,1,-1};
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n || mat[nr][nc] <= mat[r][c]) continue;
best = max(best, 1 + dfs(nr, nc));
}
return memo[r][c] = best;
};
int ans = 0;
for (int r = 0; r < m; ++r) for (int c = 0; c < n; ++c) ans = max(ans, dfs(r, c));
return ans;
}
};

Editorial#

The strictly-increasing condition turns the grid into an implicit DAG (edges from smaller to larger). DAG longest path with memoization is O(V + E). Memo on (r, c) saves us from re-exploring shared suffixes.

Complexity#

  • Time: O(m * n).
  • Space: O(m * n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.