当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

sqlserver 数据库之事物使用入门 案例

Websocket (simple experience version)

开口式霍尔电流传感器如何助力直流配电改造?

数据库系列之MySQL和TiDB中慢日志分析

音频 scipy 中 spectrogram 的运作机制

资源管理、高可用与自动化(中)

A Preliminary Study of Blackbody radiation

Resource management, high availability and automation (Part 2)

Resource management, high availability and automation (medium)

Change of monitoring documents and folders of "operation and maintenance department"
随机推荐
Anaconda命令用法
How to write anti shake throttling for small programs?
Change of monitoring documents and folders of "operation and maintenance department"
Web APIs DOM-事件基础丨黑马程序员
INFO:&nbsp; HHH000397:&nbsp; Using…
小程序的防抖节流怎么写?
A solution to the inefficiency of setting debug mode in developing flask framework with pychar
黑体辐射初探
第14章 AC-DC电源前级电路 笔记一
What is the core problem to be solved in the East and West?
Research and arrangement of electronic map coordinate system
Self use tool unity video player that monkeys can use
电学基础知识整理(二)
数字有为,易步到位 华为携“5极”明星产品加速布局商业市场
Lost connection repair: make "hide and seek" nowhere to hide
Pycharm不同项目之间共用第三方模块
Understanding and learning of parental delegation mechanism
数据库系列之MySQL和TiDB中慢日志分析
Floating point and complex type of go data type (4)
Resource management, high availability and automation (Part 2)