• Leetcode 329.矩阵中的最长递增路径


    矩阵中的最长递增路径

    给定一个整数矩阵,找出最长递增路径的长度。

    对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。

    示例 1:

    输入: nums =

    [

    [9,9,4],

    [6,6,8],

    [2,1,1]

    ]

    输出: 4

    解释: 最长递增路径为 [1, 2, 6, 9]。

    示例 2:

    输入: nums =

    [

    [3,4,5],

    [3,2,6],

    [2,2,1]

    ]

    输出: 4

    解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。

     1 class Solution {
     2     public static int n,m;
     3 
     4     public static int f[][] = new int[1000][1000];
     5 
     6     public static boolean check(int x,int y,int nx,int ny,int[][] mat){//能不能走到下一个格子,那些格子可以继续拓展
     7         return x >=0 && y>= 0 && nx >=0 && ny >=0 && x < n && y <m && nx < n && ny <m && mat[x][y] > mat[nx][ny];
     8     }
     9 
    10     public int robot(int x,int y,int[][] mat){//最远能走多少步
    11 
    12         if(f[x][y] > 0){
    13             return f[x][y];
    14         }
    15 
    16         int max = 0;
    17         for(int dx = -1;dx <= 1;dx++){
    18             for (int dy = -1;dy <= 1;dy++){
    19                 if(Math.abs(dx + dy) ==1){
    20                     if(check(x,y,x+dx,y+dy,mat))
    21                         max = Math.max(max,robot(x+dx,y+dy,mat)) ;
    22                 }
    23             }
    24         }
    25         f[x][y] = max + 1;
    26         return max+1;
    27     }
    28 
    29     //枚举最后出发的位置
    30     public int longestIncreasingPath(int[][] matrix) {
    31 
    32         n = matrix.length;
    33         if (n==0){
    34             return 0;
    35         }
    36 
    37         m = matrix[0].length;
    38 
    39         for(int i = 0;i< n;i++){
    40             for(int j = 0;j < m; j++){
    41                 f[i][j] = 0;
    42             }
    43         }
    44 
    45         int ans = 0;
    46         for(int i =0;i<n;i++){
    47             for(int j = 0;j<m;j++){
    48                 ans = Math.max(ans,robot(i,j,matrix));
    49             }
    50         }
    51         return ans;
    52     }
    53 }
  • 相关阅读:
    ASP.NET MVC 与 Web Forms
    去除两端margin的方法
    Media Queries之Respond.js
    ECMAScript5严格模式
    用rem设置文字大小
    BFC与hasLayout
    快速把项目部署到webLogic上
    判断一个坐标点是否在不规则多边形内部的算法
    Git 工作流的正确打开方式
    Java设计模式六大原则
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10235222.html
Copyright © 2020-2023  润新知