zoukankan      html  css  js  c++  java
  • 0329. Longest Increasing Path in a Matrix (H)

    Longest Increasing Path in a Matrix (H)

    题目

    Given an m x n integers matrix, return the length of the longest increasing path in matrix.

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

    Example 1:

    Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
    Output: 4
    Explanation: The longest increasing path is [1, 2, 6, 9].
    

    Example 2:

    Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
    Output: 4
    Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
    

    Example 3:

    Input: matrix = [[1]]
    Output: 1
    

    Constraints:

    • m == matrix.length
    • n == matrix[i].length
    • 1 <= m, n <= 200
    • 0 <= matrix[i][j] <= 2^31 - 1

    题意

    给定一个矩阵,可以从任一位置出发得到一条递增的路径,求最长路径的长度。

    思路

    DFS+记忆化很容易解决。


    代码实现

    Java

    class Solution {
        private int[] xShift = {0, -1, 0, 1};
        private int[] yShift = {-1, 0, 1, 0};
        private int m, n;
    
        public int longestIncreasingPath(int[][] matrix) {
            m = matrix.length;
            n = matrix[0].length;
    
            int ans = 0;
            int[][] record = new int[m][n];
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    ans = Math.max(ans, dfs(matrix, i, j, record));
                }
            }
    
            return ans;
        }
    
        private int dfs(int[][] matrix, int x, int y, int[][] record) {
            if (record[x][y] > 0) return record[x][y];
    
            record[x][y] = 1;
            for (int i = 0; i < 4; i++) {
                int nx = x + xShift[i], ny = y + yShift[i];
                if (nx >= 0 && nx < m && ny >= 0 && ny < n && matrix[x][y] < matrix[nx][ny]) {
                    record[x][y] = Math.max(record[x][y], 1 + dfs(matrix, nx, ny, record));
                }
            }
            return record[x][y];
        }
    }
    
  • 相关阅读:
    js中两种定时器,setTimeout和setInterval的区别
    简单说 JavaScript实现雪花飘落效果
    CSS 浮动 float 属性
    使用jQuery做简单的图片轮播效果
    DIV+CSS中标签dl dt dd常用的用法
    CSS display的几个常用的属性值,inline , block, inline-block
    Confluence代码块(Code Block)宏
    salt总结
    快速搭建rabbitmq单节点并配置使用
    使用python脚本配置zabbix发送报警邮件
  • 原文地址:https://www.cnblogs.com/mapoos/p/14641185.html
Copyright © 2011-2022 走看看