当前位置:网站首页>leetcode - 329. 矩阵中的最长递增路径
leetcode - 329. 矩阵中的最长递增路径
2022-06-28 03:21:00 【zmm_mohua】
leetcode - 329. 矩阵中的最长递增路径
题目

代码
#include <iostream>
#include <vector>
using namespace std;
/* 转换思路,将其看作图,当相邻的两个数不等时,就会存在一条由大值指向小值的边 那我们要找的就是图的最长路径,所以用dfs */
int m, n;
int dir[4][2] = {
{
-1, 0}, {
1, 0}, {
0, -1}, {
0, 1}};
int dfs(vector<vector<int> >& matrix, vector<vector<int> >& memo, int i, int j){
if(memo[i][j] != 0){
return memo[i][j];
}
memo[i][j]++;
for(int k = 0; k < 4; k++){
int x = i + dir[k][0];
int y = j + dir[k][1];
if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]){
memo[i][j] = max(memo[i][j], dfs(matrix, memo, x, y) + 1);
}
}
return memo[i][j];
}
int longestIncreasingPath(vector<vector<int> >& matrix) {
if(matrix.size() == 0 || matrix[0].size() == 0){
return 0;
}
m = matrix.size();
n = matrix[0].size();
int res = 1;
vector<vector<int> > memo(m, vector<int>(n, 0));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
res = max(res, dfs(matrix, memo, i, j));
}
}
return res;
}
int main(){
int m, n, res;
cin>>m>>n;
vector<vector<int> > matrix(m, vector<int>(n));
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cin>>matrix[i][j];
}
}
res = longestIncreasingPath(matrix);
cout<<res;
return 0;
}
边栏推荐
- How to modify a se38 editor theme
- What is the core problem to be solved in the East and West?
- 力扣每日一题-第29天-219.存在重复元素Ⅱ
- 图片的懒加载和预加载
- 如何系统学习一门编程语言? | 黑马程序员
- MySQL configuration of database Series F5 load balancing
- 多线程与高并发四:VarHandle与强软弱虚引用和ThreadLocal
- How does the open-ended Hall current sensor help the transformation of DC power distribution?
- 几个重要的物理概念
- English语法_形容词/副词3级 - 比较级
猜你喜欢
随机推荐
"9 No" principle and "5 measurement dimensions" of extensible system
电学基础知识整理(二)
上线MES系统后,企业发生了这些变化......
可扩展系统的“9不”原则和“5个”衡量维度
Websocket (simple experience version)
uni-app 如何根据环境自动切换请求的地址
TypeError:&nbsp;&# 039; module&amp;# 03…
Learning - useful resources
Chapter IX app project test (3) test tools
小程序image组件不显示图片?
Resource management, high availability and automation (Part 2)
leetcode:494. All methods of adding and subtracting operators to the array to get the specified value
Database migration
开口式霍尔电流传感器如何助力直流配电改造?
Arrangement of basic electrical knowledge (II)
一千行 MySQL 学习笔记,值得收藏!
A preliminary study of blackbody radiation
Backtracking maze problem
解析教育机器人的综合应用能力
力扣每日一题-第29天-1491.去掉最低工资和最高工资后的平均工资









