@@ -35,39 +35,39 @@ For each position `matrix[x][y]`,
3535* otherwise, probe the 4 directions, ` cnt[x][y] ` is one greater than its largest neightbor.
3636
3737``` 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/
3939// Author: github.com/lzl124631x
4040// Time: O(MN)
4141// Space: O(MN)
4242class 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 ] ;
5354 }
54- ans = max(ans, cnt[ x] [ y ] );
55- return cnt[ x] [ y ] ;
56- }
5755public:
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+ }
6765};
6866```
6967
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.
7171
7272```cpp
7373// OJ: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
0 commit comments