@@ -35,39 +35,39 @@ For each position `matrix[x][y]`,
35
35
* otherwise, probe the 4 directions, ` cnt[x][y] ` is one greater than its largest neightbor.
36
36
37
37
``` cpp
38
- // OJ: https://leetcode.com/problems/longest-increasing-path-in-a-matrix
38
+ // OJ: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
39
39
// Author: github.com/lzl124631x
40
40
// Time: O(MN)
41
41
// Space: O(MN)
42
42
class Solution {
43
- private:
44
- int M, N, ans = 0, dirs[ 4] [ 2 ] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
45
- vector<vector<int >> cnt;
46
- int dfs(vector<vector<int >> &matrix, int x, int y) {
47
- if (cnt[ x] [ y ] ) return cnt[ x] [ y ] ;
48
- cnt[ x] [ y ] = 1;
49
- for (auto dir : dirs) {
50
- int i = x + dir[ 0] , j = y + dir[ 1] ;
51
- if (i < 0 || i >= M || j < 0 || j >= N || matrix[ i] [ j ] <= matrix[ x] [ y ] ) continue;
52
- cnt[ x] [ y ] = max(cnt[ x] [ y ] , 1 + dfs(matrix, i, j));
43
+ vector<vector<int >> cnt;
44
+ int ans = 0, M, N, dirs[ 4] [ 2 ] = {{0,1},{0,-1},{1,0},{-1,0}};
45
+ int dfs(vector<vector<int >> &A, int x, int y) {
46
+ if (cnt[ x] [ y ] ) return cnt[ x] [ y ] ;
47
+ cnt[ x] [ y ] = 1;
48
+ for (auto &dir : dirs) {
49
+ int a = x + dir[ 0] , b = y + dir[ 1] ;
50
+ if (a < 0 || b < 0 || a >= M || b >= N || A[ a] [ b ] <= A[ x] [ y ] ) continue;
51
+ cnt[ x] [ y ] = max(cnt[ x] [ y ] , 1 + dfs(A, a, b));
52
+ }
53
+ return cnt[ x] [ y ] ;
53
54
}
54
- ans = max(ans, cnt[ x] [ y ] );
55
- return cnt[ x] [ y ] ;
56
- }
57
55
public:
58
- int longestIncreasingPath(vector<vector<int >>& matrix ) {
59
- if (matrix .empty() || matrix [ 0] .empty()) return 0;
60
- M = matrix .size(), N = matrix [ 0] .size();
61
- cnt = vector<vector< int >> (M, vector<int >(N, 0 ));
62
- for (int i = 0; i < M; ++i)
63
- for (int j = 0; j < N; ++j)
64
- dfs(matrix , i, j);
65
- return ans;
66
- }
56
+ int longestIncreasingPath(vector<vector<int >>& A ) {
57
+ if (A .empty() || A [ 0] .empty()) return 0;
58
+ M = A .size(), N = A [ 0] .size();
59
+ cnt.assign (M, vector<int >(N));
60
+ for (int i = 0; i < M; ++i)
61
+ for (int j = 0; j < N; ++j)
62
+ ans = max(ans, dfs(A , i, j) );
63
+ return ans;
64
+ }
67
65
};
68
66
```
69
67
70
- ## Solution 2. Topological Sort
68
+ ## Solution 2. Topological Sort (BFS)
69
+
70
+ Note that the DFS version of topological sort solution is the same as the Solution 1.
71
71
72
72
```cpp
73
73
// OJ: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
0 commit comments