329. Longest Increasing Path in a Matrix
Asked at 19Meta47Google38Apple35Microsoft28Amazon27Bloomberg18EPAM Systems51Infosys45Visa39DoorDash92WeRide78Duolingo74Nutanix71Adobe55PhonePe53Epic Systems51TikTok50Salesforce35Uber22
Problem
Return the length of the longest strictly increasing path in matrix, moving up, down, left or right (no diagonals, no wrapping).
Example: [[9,9,4],[6,6,8],[2,1,1]] → 4 (1 → 2 → 6 → 9)
Constraints: up to 200 × 200.
Strictly increasing paths can't cycle, so the grid is a DAG: best(r, c) = 1 + max(best(neighbor) for larger neighbours), memoized.
Complexity: O(R·C).
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
R, C = len(matrix), len(matrix[0])
@cache
def best(r, c):
v, res = matrix[r][c], 1
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and matrix[nr][nc] > v:
res = max(res, 1 + best(nr, nc))
return res
return max(best(r, c) for r in range(R) for c in range(C))
assert Solution().longestIncreasingPath([[9, 9, 4], [6, 6, 8], [2, 1, 1]]) == 4
assert Solution().longestIncreasingPath([[3, 4, 5], [3, 2, 6], [2, 2, 1]]) == 4
class Solution {
private int[][] memo;
public int longestIncreasingPath(int[][] matrix) {
int R = matrix.length, C = matrix[0].length, best = 0;
memo = new int[R][C];
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) best = Math.max(best, dfs(matrix, r, c));
return best;
}
private int dfs(int[][] m, int r, int c) {
if (memo[r][c] > 0) return memo[r][c];
int res = 1;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nc >= 0 && nr < m.length && nc < m[0].length && m[nr][nc] > m[r][c])
res = Math.max(res, 1 + dfs(m, nr, nc));
}
return memo[r][c] = res;
}
}
func longestIncreasingPath(matrix [][]int) int {
R, C := len(matrix), len(matrix[0])
memo := make([][]int, R) // longest path starting at (r, c); 0 = not computed
for i := range memo {
memo[i] = make([]int, C)
}
var best func(r, c int) int
best = func(r, c int) int {
if memo[r][c] > 0 {
return memo[r][c]
}
res := 1
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := r+d[0], c+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && matrix[nr][nc] > matrix[r][c] {
res = max(res, 1+best(nr, nc))
}
}
memo[r][c] = res
return res
}
ans := 0
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
ans = max(ans, best(r, c))
}
}
return ans
}