|
1 | 1 | class Solution {
|
2 |
| - int[][] dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
3 |
| - public int longestIncreasingPath(int[][] matrix) { |
4 |
| - if (matrix.length == 0 || matrix[0].length == 0) { |
5 |
| - return 0; |
6 |
| - } |
7 |
| - |
8 |
| - int[][] dp = new int[matrix.length][matrix[0].length]; |
9 |
| - int max = 0; |
10 |
| - for (int i = 0; i < matrix.length; i++) { |
11 |
| - for (int j = 0; j < matrix[0].length; j++) { |
12 |
| - max = Math.max(max, dfs(matrix, i, j, dp, Integer.MIN_VALUE)); |
13 |
| - } |
14 |
| - } |
15 |
| - |
16 |
| - return max; |
| 2 | + private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 3 | + |
| 4 | + public int longestIncreasingPath(int[][] matrix) { |
| 5 | + int numRows = matrix.length; |
| 6 | + int numCols = matrix[0].length; |
| 7 | + int maxPathLength = 0; |
| 8 | + int[][] cache = new int[numRows][numCols]; |
| 9 | + for (int i = 0; i < numRows; i++) { |
| 10 | + for (int j = 0; j < numCols; j++) { |
| 11 | + maxPathLength = Math.max(maxPathLength, helper(matrix, numRows, numCols, i, j, cache)); |
| 12 | + } |
17 | 13 | }
|
18 |
| - |
19 |
| - private int dfs(int[][] matrix, int x, int y, int[][] dp, int prevVal) { |
20 |
| - if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] <= prevVal) { |
21 |
| - return 0; |
22 |
| - } |
23 |
| - |
24 |
| - if (dp[x][y] != 0) { |
25 |
| - return dp[x][y]; |
26 |
| - } |
27 |
| - |
28 |
| - int temp = 0; |
29 |
| - for (int[] dir : dirs) { |
30 |
| - temp = Math.max(temp, dfs(matrix, x + dir[0], y + dir[1], dp, matrix[x][y])); |
31 |
| - } |
32 |
| - |
33 |
| - dp[x][y] = temp + 1; |
34 |
| - return dp[x][y]; |
| 14 | + return maxPathLength; |
| 15 | + } |
| 16 | + |
| 17 | + private int helper(int[][] matrix, int numRows, int numCols, int i, int j, int[][] cache) { |
| 18 | + if (cache[i][j] != 0) { |
| 19 | + return cache[i][j]; |
35 | 20 | }
|
| 21 | + for (int[] dir : DIRS) { |
| 22 | + int x = i + dir[0]; |
| 23 | + int y = j + dir[1]; |
| 24 | + if (x >= 0 && y >= 0 && x < numRows && y < numCols && matrix[x][y] > matrix[i][j]) { |
| 25 | + cache[i][j] = Math.max(cache[i][j], helper(matrix, numRows, numCols, x, y, cache)); |
| 26 | + } |
| 27 | + } |
| 28 | + return ++cache[i][j]; |
| 29 | + } |
36 | 30 | }
|
0 commit comments