Memoised DFS
Time O(rows × cols) Space O(rows × cols)memo[r][c] = 1 + max over neighbours with a larger value. Each cell is computed once.
class Solution {
private int[][] memo;
private static final int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int longestIncreasingPath(int[][] matrix) {
memo = new int[matrix.length][matrix[0].length];
int best = 0;
for (int r = 0; r < matrix.length; r++)
for (int c = 0; c < matrix[0].length; c++)
best = Math.max(best, len(matrix, r, c));
return best;
}
private int len(int[][] m, int r, int c) {
if (memo[r][c] > 0) return memo[r][c];
int best = 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]) continue;
best = Math.max(best, 1 + len(m, nr, nc));
}
return memo[r][c] = best;
}
}Verdict: DP on the implicit DAG.