当前位置:网站首页>leetcode - 329. Longest increasing path in matrix
leetcode - 329. Longest increasing path in matrix
2022-06-28 04:09:00 【zmm_ mohua】
leetcode - 329. The longest incremental path in the matrix
subject

Code
#include <iostream>
#include <vector>
using namespace std;
/* Change your mind , Think of it as a graph , When two adjacent numbers are not equal , There will be an edge from a large value to a small value What we are looking for is the longest path of the graph , So use 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;
}
边栏推荐
猜你喜欢

Detailed explanation of KVM common commands

Web APIs DOM event foundation dark horse programmer

KVM常用命令详解

《性能之巅第2版》阅读笔记(二)--性能观察工具

Meichuang was selected into the list of "2022 CCIA top 50 Chinese network security competitiveness"

Market competitiveness of robot programming education

从零到一,教你搭建「以文搜图」搜索服务(一)

Principle and Simulation of switching power supply buck circuit

Are the two flame retardant standards of European furniture en 597-1 and en 597-2 the same?

Chapter 14 AC-DC power supply front stage circuit note I
随机推荐
MySQL 主从复制、分离解析
How to apply for ASTM E108 flame retardant test for photovoltaic panels?
歐洲家具EN 597-1 跟EN 597-2兩個阻燃標准一樣嗎?
利用ELK 搭建日志分析系统(三)—— 安全认证
回溯—迷宫问题
Introduction notes to machine learning
指针链表
用一个栈实现另一个栈的排序
A solution to the inefficiency of setting debug mode in developing flask framework with pychar
ELK 搭建日志分析系统 + Zipkin服务链路追踪整合
Visualization of loss using tensorboard
Supplementary questions of monthly competition
Elk builds log analysis system + Zipkin service link tracking integration
Two methods of shell script parameter passing based on arm5718
Door level modeling - learning notes
使用信号分析器
01 MongoDB的概述、应用场景、下载方式、连接方式和发展历史等
leetcode:494.数组中添加加减运算符得到指定值的所有方法
光伏板怎么申请ASTM E108阻燃测试?
美创数据安全管理平台获信通院“数据安全产品能力验证计划”评测证书