[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.
这道题给我们一个二维数组,让我们求矩阵中最长的递增路径,规定我们只能上下左右行走,不能走斜线或者是超过了边界。那么这道题的解法要用递归和DP来解,用DP的原因是为了提高效率,避免重复运算。我们需要维护一个二维动态数组dp,其中dp[i][j]表示数组中以(i,j)为起点的最长递增路径的长度,初始将dp数组都赋为0,当我们用递归调用时,遇到某个位置(x, y), 如果dp[x][y]不为0的话,我们直接返回dp[x][y]即可,不需要重复计算。我们需要以数组中每个位置都为起点调用递归来做,比较找出最大值。在以一个位置为起点用DFS搜索时,对其四个相邻位置进行判断,如果相邻位置的值大于上一个位置,则对相邻位置继续调用递归,并更新一个最大值,搜素完成后返回即可,参见代码如下:
解法一:
- class Solution {
- public:
- vector<vector<int>> dirs = {{, -}, {-, }, {, }, {, }};
- int longestIncreasingPath(vector<vector<int>>& matrix) {
- if (matrix.empty() || matrix[].empty()) return ;
- int res = , m = matrix.size(), n = matrix[].size();
- vector<vector<int>> dp(m, vector<int>(n, ));
- for (int i = ; i < m; ++i) {
- for (int j = ; j < n; ++j) {
- res = max(res, dfs(matrix, dp, i, j));
- }
- }
- return res;
- }
- int dfs(vector<vector<int>> &matrix, vector<vector<int>> &dp, int i, int j) {
- if (dp[i][j]) return dp[i][j];
- int mx = , m = matrix.size(), n = matrix[].size();
- for (auto a : dirs) {
- int x = i + a[], y = j + a[];
- if (x < || x >= m || y < |a| y >= n || matrix[x][y] <= matrix[i][j]) continue;
- int len = + dfs(matrix, dp, x, y);
- mx = max(mx, len);
- }
- dp[i][j] = mx;
- return mx;
- }
- };
下面再来看一种BFS的解法,需要用queue来辅助遍历,我们还是需要dp数组来减少重复运算。遍历数组中的每个数字,跟上面的解法一样,把每个遍历到的点都当作BFS遍历的起始点,需要优化的是,如果当前点的dp值大于0了,说明当前点已经计算过了,我们直接跳过。否则就新建一个queue,然后把当前点的坐标加进去,再用一个变量cnt,初始化为1,表示当前点为起点的递增长度,然后进入while循环,然后cnt自增1,这里先自增1没有关系,因为只有当周围有合法的点时候才会用cnt来更新。由于当前结点周围四个相邻点距当前点距离都一样,所以采用类似二叉树层序遍历的方式,先出当前queue的长度,然后遍历跟长度相同的次数,取出queue中的首元素,对周围四个点进行遍历,计算出相邻点的坐标后,要进行合法性检查,横纵坐标不能越界,且相邻点的值要大于当前点的值,并且相邻点点dp值要小于cnt,才有更新的必要。用cnt来更新dp[x][y],并用cnt来更新结果res,然后把相邻点排入queue中继续循环即可,参见代码如下:
解法二:
- class Solution {
- public:
- int longestIncreasingPath(vector<vector<int>>& matrix) {
- if (matrix.empty() || matrix[].empty()) return ;
- int m = matrix.size(), n = matrix[].size(), res = ;
- vector<vector<int>> dirs{{,-},{-,},{,},{,}};
- vector<vector<int>> dp(m, vector<int>(n, ));
- for (int i = ; i < m; ++i) {
- for (int j = ; j < n; ++j ) {
- if (dp[i][j] > ) continue;
- queue<pair<int, int>> q{{{i, j}}};
- int cnt = ;
- while (!q.empty()) {
- ++cnt;
- int len = q.size();
- for (int k = ; k < len; ++k) {
- auto t = q.front(); q.pop();
- for (auto dir : dirs) {
- int x = t.first + dir[], y = t.second + dir[];
- if (x < || x >= m || y < || y >= n || matrix[x][y] <= matrix[t.first][t.second] || cnt <= dp[x][y]) continue;
- dp[x][y] = cnt;
- res = max(res, cnt);
- q.push({x, y});
- }
- }
- }
- }
- }
- return res;
- }
- };
参考资料:
https://discuss.leetcode.com/topic/35052/iterative-java-bfs-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Longest Increasing Path in a Matrix 矩阵中的最长递增路径的更多相关文章
- 329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径
Given an integer matrix, find the length of the longest increasing path.From each cell, you can eith ...
- Leetcode之深度优先搜索(DFS)专题-329. 矩阵中的最长递增路径(Longest Increasing Path in a Matrix)
Leetcode之深度优先搜索(DFS)专题-329. 矩阵中的最长递增路径(Longest Increasing Path in a Matrix) 深度优先搜索的解题详细介绍,点击 给定一个整数矩 ...
- Leetcode 329.矩阵中的最长递增路径
矩阵中的最长递增路径 给定一个整数矩阵,找出最长递增路径的长度. 对于每个单元格,你可以往上,下,左,右四个方向移动. 你不能在对角线方向上移动或移动到边界外(即不允许环绕). 示例 1: 输入: n ...
- Java实现 LeetCode 329 矩阵中的最长递增路径
329. 矩阵中的最长递增路径 给定一个整数矩阵,找出最长递增路径的长度. 对于每个单元格,你可以往上,下,左,右四个方向移动. 你不能在对角线方向上移动或移动到边界外(即不允许环绕). 示例 1: ...
- [Swift]LeetCode329. 矩阵中的最长递增路径 | Longest Increasing Path in a Matrix
Given an integer matrix, find the length of the longest increasing path. From each cell, you can eit ...
- LeetCode Longest Increasing Path in a Matrix
原题链接在这里:https://leetcode.com/problems/longest-increasing-path-in-a-matrix/ Given an integer matrix, ...
- LeetCode. 矩阵中的最长递增路径
题目要求: 给定一个整数矩阵,找出最长递增路径的长度. 对于每个单元格,你可以往上,下,左,右四个方向移动. 你不能在对角线方向上移动或移动到边界外(即不允许环绕). 示例: 输入: nums = [ ...
- 【LeetCode】329. Longest Increasing Path in a Matrix 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/longest- ...
- LeetCode #329. Longest Increasing Path in a Matrix
题目 Given an integer matrix, find the length of the longest increasing path. From each cell, you can ...
随机推荐
- WebApi系列~StringContent与FormUrlEncodedContent
回到目录 知识点 本文是一个很另类的文章,在项目中用的比较少,但如果项目中真的出现了这种情况,我们也需要知道如何去解决,对于知识点StringContent和FormUrlEncodedContent ...
- Navisworks Api Quantification
Quantification 国外有的叫定量 我们国内一些施工方叫工程量. 通过TakeOff API的开发者有机会获得更多的数据和数据可通过图形用户界面. 1 添加Navisworks的Api ...
- Oracle用户被锁原因及办法
Oracle用户被锁原因及办法 在登陆时被告知test用户被锁 1.用dba角色的用户登陆,进行解锁,先设置具体时间格式,以便查看具体时间 SQL> alter session set nl ...
- STL: unordered_map 自定义键值使用
使用Windows下 RECT 类型做unordered_map 键值 1. Hash 函数 计算自定义类型的hash值. struct hash_RECT { size_t operator()(c ...
- javaScript中的小细节-局部作用域中的var
javaScript中var是很神奇的,在局部作用域中,var a = b = c = 1;是不一样的,a为使用var声明的变量,而b和c则是全局下的,此类变量被称为隐式全局变量:var a = 1; ...
- 用css隐藏元素的5种方法
.green { width: 100px; height: 100px; background-color: #a0ee00; text-align: center; float: left; ma ...
- 2D动画的制作
通过css3的transform transition可以实现平移,旋转,缩放,拉伸等效果 1.缩放 -webkit-transform: scale(1); -moz-transform: sca ...
- SAP CRM 使用Javascript触发SAP Server Event
原文地址:How To Trigger SAP Server Event With Javascript 本文地址:http://www.cnblogs.com/hhelibeb/p/5977921. ...
- [Android]使用Dagger 2依赖注入 - DI介绍(翻译)
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5092083.html 使用Dagger 2依赖注入 - DI介 ...
- Android中的自定义控件(一)
自定义控件是根据自己的需要自己来编写控件.安卓自带的控件有时候无法满足你的需求,这种时候,我们只能去自己去实现适合项目的控件.同时,安卓也允许你去继承已经存在的控件或者实现你自己的控件以便优化界面和创 ...