Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3f74e52

Browse files
feat: add swift implementation to lcof2 problem: No.112 (doocs#3690)
1 parent c57ccae commit 3f74e52

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

‎lcof2/剑指 Offer II 112. 最长递增路径/README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,49 @@ func longestIncreasingPath(matrix [][]int) int {
205205
}
206206
```
207207

208+
#### Swift
209+
210+
```swift
211+
class Solution {
212+
private var memo: [[Int]] = []
213+
private var matrix: [[Int]] = []
214+
private var m: Int = 0
215+
private var n: Int = 0
216+
217+
func longestIncreasingPath(_ matrix: [[Int]]) -> Int {
218+
self.matrix = matrix
219+
m = matrix.count
220+
n = matrix[0].count
221+
memo = Array(repeating: Array(repeating: -1, count: n), count: m)
222+
223+
var ans = 0
224+
for i in 0..<m {
225+
for j in 0..<n {
226+
ans = max(ans, dfs(i, j))
227+
}
228+
}
229+
return ans
230+
}
231+
232+
private func dfs(_ i: Int, _ j: Int) -> Int {
233+
if memo[i][j] != -1 {
234+
return memo[i][j]
235+
}
236+
var ans = 1
237+
let dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
238+
239+
for (dx, dy) in dirs {
240+
let x = i + dx, y = j + dy
241+
if x >= 0, x < m, y >= 0, y < n, matrix[x][y] > matrix[i][j] {
242+
ans = max(ans, dfs(x, y) + 1)
243+
}
244+
}
245+
memo[i][j] = ans
246+
return ans
247+
}
248+
}
249+
```
250+
208251
<!-- tabs:end -->
209252

210253
<!-- solution:end -->
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
private var memo: [[Int]] = []
3+
private var matrix: [[Int]] = []
4+
private var m: Int = 0
5+
private var n: Int = 0
6+
7+
func longestIncreasingPath(_ matrix: [[Int]]) -> Int {
8+
self.matrix = matrix
9+
m = matrix.count
10+
n = matrix[0].count
11+
memo = Array(repeating: Array(repeating: -1, count: n), count: m)
12+
13+
var ans = 0
14+
for i in 0..<m {
15+
for j in 0..<n {
16+
ans = max(ans, dfs(i, j))
17+
}
18+
}
19+
return ans
20+
}
21+
22+
private func dfs(_ i: Int, _ j: Int) -> Int {
23+
if memo[i][j] != -1 {
24+
return memo[i][j]
25+
}
26+
var ans = 1
27+
let dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
28+
29+
for (dx, dy) in dirs {
30+
let x = i + dx, y = j + dy
31+
if x >= 0, x < m, y >= 0, y < n, matrix[x][y] > matrix[i][j] {
32+
ans = max(ans, dfs(x, y) + 1)
33+
}
34+
}
35+
memo[i][j] = ans
36+
return ans
37+
}
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /