1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { private int[][] DIRECTIONS = new int[][] { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
public int longestIncreasingPath(int[][] matrix) { int[][] cache = new int[matrix.length][matrix[0].length]; int max = -1; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { max = Math.max(max, dfs(matrix, i, j, cache)); } } return max; }
private int dfs(int[][] matrix, int row, int col, int[][] cache) { if (cache[row][col] != 0) { return cache[row][col]; } int maxLength = 1; for (int[] direction : DIRECTIONS) { int newRow = row + direction[0]; int newCol = col + direction[1]; if (!isOutOfBound(matrix, newRow, newCol) && matrix[row][col] < matrix[newRow][newCol]) { maxLength = Math.max(maxLength, 1 + dfs(matrix, newRow, newCol, cache)); } } cache[row][col] = maxLength; return cache[row][col]; }
private boolean isOutOfBound(int[][] matrix, int row, int col) { return row < 0 || row >= matrix.length || col < 0 || col >= matrix[0].length; } }
|