1+ // https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/
2+
3+ #pragma once
4+
5+ #include < algorithm>
6+ #include < iostream>
7+ #include < queue>
8+ #include < vector>
9+
10+ using namespace std ;
11+
12+ class Solution {
13+ public:
14+ int res = 0 ;
15+ int dir[5 ] = {0 , 1 , 0 , -1 , 0 };
16+ int M, N;
17+ int dfs (vector<vector<int >> &dp, vector<vector<int >> &matrix, int x, int y,
18+ int len) {
19+ if (dp[x][y] != -1 )
20+ return dp[x][y];
21+ // int tmp = len;
22+ for (int i = 0 ; i < 4 ; i++) {
23+ int tx = x + dir[i];
24+ int ty = y + dir[i + 1 ];
25+ if (tx >= 0 && tx < M && ty >= 0 && ty < N) {
26+ if (matrix[tx][ty] > matrix[x][y]) {
27+ dp[x][y] = max (dp[x][y], dfs (dp, matrix, tx, ty, len + 1 ));
28+ }
29+ }
30+ }
31+ return ++dp[x][y];
32+ }
33+ int longestIncreasingPath (vector<vector<int >> &matrix) {
34+ if (matrix.empty () || matrix.front ().size ())
35+ return 0 ;
36+ M = matrix.size (), N = matrix.front ().size ();
37+ vector<vector<int >> dp (M, vector<int >(N, -1 ));
38+ for (int i = 0 ; i < M; i++) {
39+ for (int j = 0 ; j < N; j++) {
40+ res = max (res, dfs (dp, matrix, i, j, 1 ));
41+ }
42+ }
43+ return ++res;
44+ }
45+ };
46+
47+ inline void test () {
48+ Solution solution;
49+ cout << solution.longestIncreasingPath ({{9 , 9 , 4 }, {6 , 6 , 8 }, {2 , 1 , 1 }})
50+ << endl; // 4
51+ cout << solution.longestIncreasingPath ({{3 , 4 , 5 }, {3 , 2 , 6 }, {2 , 2 , 1 }})
52+ << endl; // 4
53+ cout << solution.longestIncreasingPath (
54+ {{0 , 0 , 12 , 6 , 15 , 1 , 12 , 10 , 12 , 10 , 6 },
55+ {6 , 19 , 6 , 13 , 5 , 18 , 17 , 19 , 7 , 11 , 13 },
56+ {8 , 6 , 9 , 1 , 15 , 7 , 10 , 10 , 3 , 7 , 18 },
57+ {2 , 14 , 12 , 10 , 17 , 2 , 3 , 10 , 4 , 8 , 3 },
58+ {8 , 2 , 19 , 3 , 19 , 10 , 17 , 18 , 12 , 10 , 8 },
59+ {0 , 17 , 14 , 12 , 10 , 4 , 8 , 17 , 15 , 11 , 19 },
60+ {13 , 6 , 14 , 8 , 16 , 19 , 12 , 17 , 16 , 17 , 8 },
61+ {7 , 4 , 6 , 8 , 3 , 9 , 19 , 12 , 4 , 13 , 0 },
62+ {18 , 0 , 16 , 12 , 10 , 11 , 8 , 14 , 6 , 3 , 0 },
63+ {10 , 3 , 14 , 17 , 19 , 18 , 10 , 2 , 11 , 5 , 19 },
64+ {6 , 2 , 2 , 1 , 8 , 1 , 11 , 7 , 7 , 18 , 1 },
65+ {11 , 12 , 16 , 0 , 9 , 6 , 8 , 3 , 12 , 8 , 15 },
66+ {5 , 18 , 17 , 4 , 11 , 9 , 9 , 6 , 8 , 2 , 4 },
67+ {3 , 12 , 7 , 2 , 9 , 17 , 14 , 10 , 14 , 5 , 0 }})
68+ << endl;
69+ }
0 commit comments