• 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];
        }
    }
    
  • 相关阅读:
    U盘启动盘的制作与U盘重装系统
    如何使用鲁大师进行驱动备份
    电子科大POJ "3*3矩阵的乘法"
    数字图像处理之sobel边缘检测
    (续)一个demo弄清楚位图在内存中的存储结构
    VC++6.0出现no compile tool is associated with the extension.解决方法
    显卡参数简单介绍
    数字图像处理之位图在计算机中的存储结构
    图像处理之边缘检测概述
    linux下mysql数据库的操作
  • 原文地址:https://www.cnblogs.com/mapoos/p/14641185.html
Copyright © 2020-2023  润新知