-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path329-longest-increasing-path-in-a-matrix.cpp
52 lines (51 loc) · 1.29 KB
/
329-longest-increasing-path-in-a-matrix.cpp
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
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int row = matrix.size();
if (row == 0)
{
return 0;
}
int col = matrix[0].size();
if (col == 0)
{
return 0;
}
vector<vector<int>> res(row, vector<int>(col, 0));
int m = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
m = max(m, cal(i, j, matrix, res));
}
}
return m;
}
int cal(int i, int j, vector<vector<int>>& matrix, vector<vector<int>>& res)
{
if (res[i][j])
{
return res[i][j];
}
int row = matrix.size();
int col = matrix[0].size();
int _x[4] = {0, 1, 0, -1};
int _y[4] = {1, 0, -1, 0};
for (int k = 0; k < 4; k++)
{
int _i = i + _x[k];
int _j = j + _y[k];
if ((_i == -1) || (_j == -1) || (_i == row) || (_j == col))
{
continue;
}
if (matrix[i][j] < matrix[_i][_j])
{
res[i][j] = max(res[i][j], cal(_i, _j, matrix, res));
}
}
res[i][j]++;
return res[i][j];
}
};