Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
Example 1:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Solution:
class Solution {
private static final int[] dx = new int[]{0,1,0,-1};
private static final int[] dy = new int[]{1,0,-1,0};
public int longestIncreasingPath(int[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
if (n == 0) return 0;
int[] max = new int[1];
int[][] memo = new int[m][n];
for (int i = 0; i < m; i ++) {
for (int j = 0; j < n; j ++) {
dfs(matrix, m, n, i, j, max, memo);
}
}
// for (int[] arr : memo) System.out.println(Arrays.toString(arr));
return max[0];
}
private int dfs(int[][] matrix, int m, int n, int i, int j, int[] max, int[][] memo) {
if (memo[i][j] > 0) return memo[i][j];
memo[i][j] = 1;
for (int k = 0; k < 4; k ++) {
int nx = i + dx[k];
int ny = j + dy[k];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && matrix[nx][ny] > matrix[i][j]) {
memo[i][j] = Math.max(memo[i][j], 1 + dfs(matrix, m, n, nx, ny, max, memo));
}
}
max[0] = Math.max(max[0], memo[i][j]);
return memo[i][j];
}
}