Skip to content

feat: add swift implementation to lcof2 problem: No.112 #3690

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions lcof2/剑指 Offer II 112. 最长递增路径/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,49 @@ func longestIncreasingPath(matrix [][]int) int {
}
```

#### Swift

```swift
class Solution {
private var memo: [[Int]] = []
private var matrix: [[Int]] = []
private var m: Int = 0
private var n: Int = 0

func longestIncreasingPath(_ matrix: [[Int]]) -> Int {
self.matrix = matrix
m = matrix.count
n = matrix[0].count
memo = Array(repeating: Array(repeating: -1, count: n), count: m)

var ans = 0
for i in 0..<m {
for j in 0..<n {
ans = max(ans, dfs(i, j))
}
}
return ans
}

private func dfs(_ i: Int, _ j: Int) -> Int {
if memo[i][j] != -1 {
return memo[i][j]
}
var ans = 1
let dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for (dx, dy) in dirs {
let x = i + dx, y = j + dy
if x >= 0, x < m, y >= 0, y < n, matrix[x][y] > matrix[i][j] {
ans = max(ans, dfs(x, y) + 1)
}
}
memo[i][j] = ans
return ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
38 changes: 38 additions & 0 deletions lcof2/剑指 Offer II 112. 最长递增路径/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
private var memo: [[Int]] = []
private var matrix: [[Int]] = []
private var m: Int = 0
private var n: Int = 0

func longestIncreasingPath(_ matrix: [[Int]]) -> Int {
self.matrix = matrix
m = matrix.count
n = matrix[0].count
memo = Array(repeating: Array(repeating: -1, count: n), count: m)

var ans = 0
for i in 0..<m {
for j in 0..<n {
ans = max(ans, dfs(i, j))
}
}
return ans
}

private func dfs(_ i: Int, _ j: Int) -> Int {
if memo[i][j] != -1 {
return memo[i][j]
}
var ans = 1
let dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]

for (dx, dy) in dirs {
let x = i + dx, y = j + dy
if x >= 0, x < m, y >= 0, y < n, matrix[x][y] > matrix[i][j] {
ans = max(ans, dfs(x, y) + 1)
}
}
memo[i][j] = ans
return ans
}
}
Loading