@@ -75,12 +75,8 @@ class Solution:
75
75
ans = max (ans, dfs(x, y) + 1 )
76
76
return ans
77
77
78
- ans = 0
79
78
m, n = len (matrix), len (matrix[0 ])
80
- for i in range (m):
81
- for j in range (n):
82
- ans = max (ans, dfs(i, j))
83
- return ans
79
+ return max (dfs(i, j) for i in range (m) for j in range (n))
84
80
```
85
81
86
82
### ** Java**
@@ -89,7 +85,6 @@ class Solution:
89
85
90
86
``` java
91
87
class Solution {
92
-
93
88
private int [][] memo;
94
89
private int [][] matrix;
95
90
private int m;
@@ -117,24 +112,17 @@ class Solution {
117
112
return memo[i][j];
118
113
}
119
114
int ans = 1 ;
120
- int [][] dirs = { { 0 , - 1 }, { 0 , 1 }, { 1 , 0 }, { - 1 , 0 } };
121
- for (int [] dir : dirs) {
122
- int x = i + dir[0 ], y = j + dir[1 ];
123
- if (
124
- x >= 0 &&
125
- x < m &&
126
- y >= 0 &&
127
- y < n &&
128
- matrix[x][y] > matrix[i][j]
129
- ) {
115
+ int [] dirs = {- 1 , 0 , 1 , 0 , - 1 };
116
+ for (int k = 0 ; k < 4 ; ++ k) {
117
+ int x = i + dirs[k], y = j + dirs[k + 1 ];
118
+ if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) {
130
119
ans = Math . max(ans, dfs(x, y) + 1 );
131
120
}
132
121
}
133
122
memo[i][j] = ans;
134
123
return ans;
135
124
}
136
125
}
137
-
138
126
```
139
127
140
128
### ** C++**
@@ -162,10 +150,10 @@ public:
162
150
int dfs (int i, int j) {
163
151
if (memo[ i] [ j ] != -1) return memo[ i] [ j ] ;
164
152
int ans = 1;
165
- vector<vector< int >> dirs = {{0, -1}, { 0, 1}, {1, 0}, {-1, 0} };
166
- for (auto& dir : dirs )
153
+ vector<int > dirs = {-1, 0, 1, 0, -1 };
154
+ for (int k = 0; k < 4; ++k )
167
155
{
168
- int x = i + dir [ 0 ] , y = j + dir [ 1] ;
156
+ int x = i + dirs [ k ] , y = j + dirs [ k + 1] ;
169
157
if (x >= 0 && x < m && y >= 0 && y < n && matrix[ x] [ y ] > matrix[ i] [ j ] )
170
158
ans = max(ans, dfs(x, y) + 1);
171
159
}
@@ -194,9 +182,9 @@ func longestIncreasingPath(matrix [][]int) int {
194
182
return memo[i][j]
195
183
}
196
184
ans := 1
197
- dirs := [4][2] int{{ -1, 0}, { 1, 0}, {0, 1}, {0, -1} }
198
- for _, dir := range dirs {
199
- x, y := i+dir[0 ], j+dir[ 1]
185
+ dirs := [] int{-1, 0, 1, 0, -1 }
186
+ for k := 0; k < 4; k++ {
187
+ x, y := i+dirs[k ], j+dirs[k+ 1]
200
188
if x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j] {
201
189
ans = max(ans, dfs(x, y)+1)
202
190
}
0 commit comments