329.Longest Increasing Path in a Matrix
1-DFS + Memorization
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/78308/
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/solution/
class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length < 1)
return 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] memo = new int[m][n]; // memory table;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1,}, {0, +1}};//four directions;
int maxLength = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int currentLength = dfs(matrix, memo, directions, i, j);
maxLength = Math.max(currentLength, maxLength);
}
}
return maxLength;
}
public int dfs(int[][] matrix, int[][] memo, int[][] directions, int x, int y){
if(memo[x][y] > 0)
return memo[x][y];
else{
int maxLength = 1;
for(int[] dir : directions){
int newX = x + dir[0];
int newY = y + dir[1];
if(newX < 0 || newX >= matrix.length || newY < 0 || newY >= matrix[0].length || matrix[newX][newY] <= matrix[x][y])
continue;
else{
int length = 1 + dfs(matrix, memo, directions, newX, newY);
maxLength = Math.max(length, maxLength);
}
}
memo[x][y] = maxLength;
return maxLength;
}
}
}