Skip to content
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