• 329. Longest Increasing Path in a Matrix


    1、题目描述

    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:

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

    2、解题思路:

    转载:Herbert_Zero

    DFS+记忆化搜索
    从起点开始遍历矩阵,递归寻找其最长递增路径。
    定义辅助数组record,用于记录已经搜索过的矩阵元素的数据,如record[x][y]存储了从坐标(x, y)出发的最长递增路径长度。
    之后,进行深度优先搜索。逐一检查某个元素的四个方向,并继续从所有可能出现最长路径的方向上进行搜索。
    当遇到record[x][y]已算出的情况,直接返回record[x][y],减少运算量。

    3、示例代码:

    class Solution {
    
    public:
        int longestIncreasingPath(vector<vector<int>>& matrix) {
            if (matrix.size() == 0) return 0;
            vector<int> temp(matrix[0].size(), 0);
            vector<vector<int>> record(matrix.size(), temp);
            int longest = 0;
            for (int i = 0; i < matrix.size(); i++) {
                for (int j = 0; j < matrix[0].size(); j++) {
                    longest = max(longest, DFS(matrix, record, i, j, -1));
                }
            }
            return longest;
        }
        int DFS(vector<vector<int> >& matrix, vector<vector<int> >& record, int x, int y, int lastVal) {
    
            if (x < 0 || y < 0 || x >= matrix.size() || y >= matrix[0].size()) return 0;
            if (matrix[x][y] > lastVal) {
                if (record[x][y] != 0) return record[x][y];
                int left = DFS(matrix, record, x - 1, y, matrix[x][y]);
                int right = DFS(matrix, record, x + 1, y, matrix[x][y]);
                int up = DFS(matrix, record, x, y + 1, matrix[x][y]);
                int bottom = DFS(matrix, record, x, y - 1, matrix[x][y]);
                record[x][y] = max(left, max(right, max(up, bottom))) + 1;
                return record[x][y];
    
            }
    
            return 0;
    
        }
    
    };
  • 相关阅读:
    Centos7安装teamviewer 32/64位
    Centos7安装32位库用来安装32位软件程序
    linux环境下配置mysql双主复制
    zabbix自定义触发器进行监控
    VM安装系统时提示硬件不支持(unsupported hardware detected)
    mysql新建用户在本地无法登录
    msyql开启慢查询以及分析慢查询
    zabbix怎么把英文界面换成中文
    xencenter如何安装系统
    mysql优化查询
  • 原文地址:https://www.cnblogs.com/fuqia/p/9700043.html
Copyright © 2020-2023  润新知