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:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
思路:DFS,对于每个点进行dfs,然后传递pre和当前的比较,然后用dp cache住以前的结果,这样提高速度;注意是matrix<= pre; return. dp[i][j] 表示的物理意义是当前这个点,能够形成的最长递增的长度。这题跟Walls and Gates很类似。T: O(M * N) , S: O(M * N)
class Solution {
public int longestIncreasingPath(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
for(int i = 0; i < m; i++) {
Arrays.fill(dp[i], -1);
}
int globalmax = 1;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
globalmax = Math.max(globalmax, dfs(matrix, i, j, dp));
}
}
return globalmax;
}
private int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
private int dfs(int[][] matrix, int x, int y, int[][] dp) {
int m = matrix.length;
int n = matrix[0].length;
if(dp[x][y] != -1) {
return dp[x][y];
}
int value = 1;
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && matrix[nx][ny] > matrix[x][y]) {
value = Math.max(value, dfs(matrix, nx, ny, dp) + 1);
}
}
dp[x][y] = value;
return dp[x][y];
}
}