329. Longest Increasing Path in a Matrix

来源:互联网 发布:象过河软件怎么使用 编辑:程序博客网 时间:2024/05/22 19:27

329. Longest Increasing Path in a Matrix

leetcode Longest Increasing Path in a Matrix

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:

nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]

Return 4
The longest increasing path is [1, 2, 6, 9].

Example 2:

nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]

Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

题目地址:Longest Increasing Path in a Matrix

题意:给定一个矩阵,在里面找出最大上升路径

思路:

记忆化DFS。

设dis[i][j]为从点[i][j]出发的最大上升路径。初始值设置为0,表示该点未被访问过,需要更新,再次碰到的时候,元素值必定不为0,表示已被访问过,只需要返回该值即可。这样做就将标记元素是否访问过的功能和记录从该元素出发最大上升路径的功能合二为一,节省空间,值得借鉴。

利用DFS算法,遍历矩阵中的每个元素,当前元素的最大上升路径为周围四个元素的最大上升路径+1。

注意递推的条件:

  1. 元素未被访问过
  2. 元素下标不越界
  3. 元素的值要比其父元素的值大

C++

//1、全局变量的使用:在leetcode中要使用全局变量,在类外声明。//2、在dfs算法中,将每步需要搜遍的点写成数组的形式是经常使用的技巧,方便遍历。int dx[] = {1,-1,0,0};int dy[] = {0,0,1,-1};class Solution{    public://3、const int & 的用法。        int dfs(int x,int y,const int &m,const int &n,vector<vector<int>>& matrix,vector<vector<int>>& dis){                    if (dis[x][y]) return dis[x][y];        for (int i = 0;i < 4; ++i){            int nx = x + dx[i];            int ny = y + dy[i];//递归搜索周围的元素。取上下左右四个元素中的dis最大者+1,作为该元素的dis值。            if (nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] > matrix[x][y]) {            dis[x][y] = max(dis[x][y], dfs(nx,ny,m,n,matrix,dis));            }        }        return ++dis[x][y];    }    int longestIncreasingPath(vector<vector<int>>& matrix){        if (!matrix.size()) return 0;        int m = matrix.size(),n = matrix[0].size();//4、vector<vector<int> >初始化的方法:变量名(行数,vector<int>(列数,初始化值))        vector<vector<int> > dis(m, vector<int>(n, 0));        int ans = 0;        for (int i = 0; i < m; i++) {            for (int j = 0; j < n; j++) {                ans = max(ans, dfs(i,j,m,n,matrix,dis));            }        }        return ans;    }};

C++知识点

常引用:

定义引用时,可以在前面加“const”关键字,则该引用就成为“常引用”。例如:

int n;const int & r = n;

就定义了常引用r,其类型是const int &。

常引用和普通引用的区别

不同通过常引用去修改其引用的内容。注意,不是常引用所引用的内容不能被修改,只是不能通过常引用修改其引用的内容而已,可以用别的办法修改。

参考:细语呢喃 > leetcode Longest Increasing Path in a Matrix

0 0