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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| class Solution { public int longestIncreasingPath(int[][] matrix) { int[][] counts = new int[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { search(matrix, counts, i, j); } }
int result = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { result = Math.max(result, counts[i][j]); } }
return result; }
private int search(int[][] matrix, int[][] counts, int i, int j) { if (counts[i][j] != 0) { return counts[i][j]; }
int num = matrix[i][j]; int left = 0; if (isMove(matrix, num, i, j - 1)) { left = search(matrix, counts, i, j - 1); }
int right = 0; if (isMove(matrix, num, i, j + 1)) { right = search(matrix, counts, i, j + 1); }
int top = 0; if (isMove(matrix, num, i - 1, j)) { top = search(matrix, counts, i - 1, j); }
int down = 0; if (isMove(matrix, num, i + 1, j)) { down = search(matrix, counts, i + 1, j); }
counts[i][j] = Math.max(Math.max(Math.max(left, right), Math.max(top, down)) + 1, counts[i][j]); return counts[i][j]; }
private boolean isMove(int[][] matrix, int num, int i, int j) { return i >=0 && i < matrix.length && j >=0 && j < matrix[0].length && num < matrix[i][j]; } }
|