[leetcode]329. Longest Increasing Path in a Matrix

心已赠人 2022-06-09 01:42 241阅读 0赞

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

  1. nums = [
  2. [9,9,4],
  3. [6,6,8],
  4. [2,1,1]
  5. ]

Return 4

The longest increasing path is [1, 2, 6, 9].

我们需要找到一个数组中的最长递增路径,这条路径可以往上下左右延伸,但是不能超出边界。

看到这一题首先可以想到深度优先搜索。要想求得最长递增路径,只需把从每一个结点开始的最长递增序列求得,然后取最大值即可。但这里的深度优先搜索寻找下一个结点的条件是必须保证下一个结点的val大于当前结点,我们可以用递归来实现。另外,我们发现并不是每个结点都能作为一条最长递增路径的首结点:当某个结点p周围有比它小的结点w存在时,p一定不能作为最长递增路径的首结点,因为把w加到p之前,我们得到一条更长的递增路径。

接下来就是实现了,我们可以用一个depth[i][j]数组保存以结点nums[i, j]为首结点的最长递增路径的长度,这样就避免了重复计算。

  1. class Solution {
  2. public int longestIncreasingPath(int[][] matrix) {
  3. if(matrix.length == 0)
  4. return 0;
  5. int max = Integer.MIN_VALUE;
  6. int[][] depth = new int[matrix.length][matrix[0].length];
  7. for(int i = 0; i < matrix.length; i++){
  8. for(int j = 0; j < matrix[0].length; j++){
  9. depth[i][j] = -1;
  10. }
  11. }
  12. for(int i = 0; i < matrix.length; i++){
  13. for(int j = 0; j < matrix[0].length; j++){
  14. if(!hasSmaller(i, j, matrix)){
  15. int deep = (depth[i][j] == -1 ? depthSearch(i, j, matrix, depth) : depth[i][j]);
  16. max = deep > max ? deep : max;
  17. }
  18. }
  19. }
  20. return max;
  21. }
  22. public boolean hasSmaller(int i, int j, int[][] matrix){
  23. if(i != 0 && matrix[i][j] > matrix[i-1][j])
  24. return true;
  25. if(i != matrix.length-1 && matrix[i][j] > matrix[i+1][j])
  26. return true;
  27. if(j != 0 && matrix[i][j] > matrix[i][j-1])
  28. return true;
  29. if(j != matrix[0].length-1 && matrix[i][j] > matrix[i][j+1])
  30. return true;
  31. return false;
  32. }
  33. public int depthSearch(int i, int j, int[][] matrix, int[][] depth){
  34. int max = Integer.MIN_VALUE;
  35. if(i != 0 && matrix[i][j] < matrix[i-1][j]){
  36. int temp = (depth[i-1][j] == -1 ? depthSearch(i-1, j, matrix, depth) : depth[i-1][j]) + 1;
  37. max = temp > max ? temp : max;
  38. }
  39. if(i != matrix.length-1 && matrix[i][j] < matrix[i+1][j]){
  40. int temp = (depth[i+1][j] == -1 ? depthSearch(i+1, j, matrix, depth) : depth[i+1][j]) + 1;
  41. max = temp > max ? temp : max;
  42. }
  43. if(j != 0 && matrix[i][j] < matrix[i][j-1]){
  44. int temp = (depth[i][j-1] == -1 ? depthSearch(i, j-1, matrix, depth) : depth[i][j-1]) + 1;
  45. max = temp > max ? temp : max;
  46. }
  47. if(j != matrix[0].length-1 && matrix[i][j] < matrix[i][j+1]){
  48. int temp = (depth[i][j+1] == -1 ? depthSearch(i, j+1, matrix, depth) : depth[i][j+1]) + 1;
  49. max = temp > max ? temp : max;
  50. }
  51. depth[i][j] = (max == Integer.MIN_VALUE ? 1 : max);
  52. return depth[i][j];
  53. }
  54. }

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读