-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlongestIncreasingPathInMatrix.h
63 lines (61 loc) · 2.07 KB
/
longestIncreasingPathInMatrix.h
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
55
56
57
58
59
60
61
62
63
//
// Created by so_go on 2019/6/16.
//
#ifndef SRC_LONGESTINCREASINGPATHINMATRIX_H
#define SRC_LONGESTINCREASINGPATHINMATRIX_H
#include<vector>
#include"printMatrix.h"
using namespace std;
class LongestIncreasingPathinMatrix {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if( matrix.size() == 0){
return 0;
}
if(matrix[0].size() == 0){
return 0;
}
int nrows = matrix.size(), ncols = matrix[0].size();
vector<vector<int>> dp(nrows, vector<int>(ncols, 1));
vector<vector<int>> dp_st = dp;
bool ischange = true;
int cur, cur_dp;
while(ischange){
ischange = false;
for(int i = 0; i < nrows; i++){
for(int j = 0; j < ncols; j++){
cur = matrix[i][j];
cur_dp = dp[i][j];
if( i > 0 and matrix[i - 1][j] < cur and 1 + dp[i - 1][j] > cur_dp){
cur_dp = 1 + dp[i-1][j];
ischange = true;
}
if( i < nrows - 1 and matrix[i + 1][j] < cur and 1 + dp[i + 1][j] > cur_dp){
cur_dp = 1 + dp[i + 1][j];
ischange = true;
}
if( j > 0 and matrix[i][j - 1] < cur and 1 + dp[i][j - 1] > cur_dp){
cur_dp = 1 + dp[i][j - 1];
ischange = true;
}
if( j < ncols - 1 and matrix[i][j + 1] < cur and 1 + dp[i][j + 1] > cur_dp){
cur_dp = 1 + dp[i][j + 1];
ischange = true;
}
dp_st[i][j] = cur_dp;
}
}
dp = dp_st;
// printMatrix(dp);
}
int max = 0;
for(int i = 0; i < nrows; i++)
for(int j = 0; j < ncols; j++){
if(dp[i][j] > max){
max = dp[i][j];
}
}
return max;
}
};
#endif //SRC_LONGESTINCREASINGPATHINMATRIX_H