zoukankan      html  css  js  c++  java
  • 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;
    
        }
    
    };
  • 相关阅读:
    进行代码复审训练
    源代码管理工具调查
    软工作业PSP与单元测试训练
    P18 第四题
    开学第一课
    进行代码复审训练
    源代码管理工具调查
    软工 任务2
    软工课后作业01 P18第四题
    课堂作业1--自我介绍
  • 原文地址:https://www.cnblogs.com/fuqia/p/9700043.html
Copyright © 2011-2022 走看看