|
| 1 | +package code; |
| 2 | +/* |
| 3 | + * 329. Longest Increasing Path in a Matrix |
| 4 | + * 题意:寻找最长的递增路径 |
| 5 | + * 难度:Hard |
| 6 | + * 分类:Depth-first Search, Topological Sort, Memoization |
| 7 | + * 思路:带记忆的dfs,之前计算的最优解可以直接合并 |
| 8 | + * Tips: |
| 9 | + */ |
| 10 | +public class lc329 { |
| 11 | + public int longestIncreasingPath(int[][] matrix) { |
| 12 | + if(matrix.length==0) return 0; |
| 13 | + int[][] cache = new int[matrix.length][matrix[0].length]; //存储计算过的结果 |
| 14 | + int res = 0; |
| 15 | + for (int i = 0; i < matrix.length ; i++) { |
| 16 | + for (int j = 0; j < matrix[0].length ; j++) { |
| 17 | + res = Math.max(dfs(matrix, i, j, cache), res); |
| 18 | + } |
| 19 | + } |
| 20 | + return res; |
| 21 | + } |
| 22 | + |
| 23 | + public int dfs(int[][] matrix, int i, int j, int[][] cache){ |
| 24 | + int max = 1; |
| 25 | + if(cache[i][j]!=0) return cache[i][j]; |
| 26 | + if( i>0 && matrix[i-1][j]>matrix[i][j]) max = Math.max(dfs(matrix, i-1, j, cache)+1, max); |
| 27 | + if( j>0 && matrix[i][j-1]>matrix[i][j]) max = Math.max(dfs(matrix, i, j-1, cache)+1, max); |
| 28 | + if( i+1<matrix.length && matrix[i+1][j]>matrix[i][j]) max = Math.max(dfs(matrix, i+1, j, cache)+1, max); |
| 29 | + if( j+1<matrix[0].length && matrix[i][j+1]>matrix[i][j]) max = Math.max(dfs(matrix, i, j+1, cache)+1, max); |
| 30 | + cache[i][j] = max; |
| 31 | + return max; |
| 32 | + } |
| 33 | +} |
0 commit comments