【leetcode】 329 Longest Increasing Path in a Matrix

二维最长递增序列


描述

给一个矩阵,求最长递增序列的长度(因为没有规定起点,其实递增和递减都一样)。

样例

1
2
3
4
5
6
7
输入:nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4 the roote is 9 6 2 1

思路

记忆深度优先搜索,遍历每个结点并令它作为起点,比较得出最大值。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
private:
int row_max;
int col_max;
vector<vector<int>>dp;
vector<vector<int>> matrix;
// dfs
int helper(int i, int j) {
int ans = 0;
if (dp[i][j] != 0) { return dp[i][j]; }
//up
if (i - 1 >= 0 && matrix[i-1][j] > matrix[i][j]) {
ans = std::max( ans,helper(i-1, j )+1);
}
//down
if (i + 1 < row_max && matrix[i+1][j ] > matrix[i][j]) {
ans = std::max(ans, helper(i+1, j ) + 1);
}
//left
if (j - 1 >= 0 && matrix[i][j - 1] > matrix[i][j]) {
ans = std::max(ans, helper(i, j - 1) + 1);
}
//right
if (j + 1 < col_max && matrix[i][j + 1] > matrix[i][j]) {
ans = std::max(ans, helper(i, j + 1) + 1);
}
return dp[i][j] = ans;
}
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.size() == 0) { return 0; }
row_max = matrix.size();
col_max = matrix[0].size();

// init the dp array
for (int i = 0; i < row_max; i++) {
dp.push_back(vector<int>{});
for (int j = 0; j < col_max; j++) {
dp[i].push_back(0);
}
}
this->matrix = matrix;
int ans = 1 << 31;

// go through each val as head
// and finally get the max value.
for (int i = 0; i < row_max; i++) {
for (int j = 0; j < col_max; j++) {
ans = max(ans, helper(i, j) + 1);
}
}
return ans;
}
};

参考

原题链接