☹️longest increasing path in matrix
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/
class Solution {
Map<String, Integer> map = new HashMap<>();
int[][] DIR = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int longestIncreasingPath(int[][] matrix) {
int ans = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
ans = Math.max(ans, dfs(matrix, i, j));
}
}
return ans;
}
private int dfs(int[][] matrix, int i, int j) {
String res = i + " " + j;
if (map.containsKey(res)) {
return map.get(res);
}
int ans = 1;
for (int[] dir : DIR) {
int x = i + dir[0];
int y = j + dir[1];
if (x >= matrix.length || x < 0 || y >= matrix[0].length || y < 0)
continue;
if (matrix[x][y] <= matrix[i][j])
continue;
ans = Math.max(ans, dfs(matrix, x, y) + 1);
}
map.put(res, ans);
return ans;
}
}Last updated