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
38 changes: 38 additions & 0 deletions lcof2/剑指 Offer II 107. 矩阵中的距离/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,44 @@ func updateMatrix(mat [][]int) [][]int {
}
```

#### Swift

```swift
class Solution {
func updateMatrix(_ mat: [[Int]]) -> [[Int]] {
let m = mat.count
let n = mat[0].count
var ans = Array(repeating: Array(repeating: -1, count: n), count: m)
var queue = [(Int, Int)]()

for i in 0..<m {
for j in 0..<n {
if mat[i][j] == 0 {
ans[i][j] = 0
queue.append((i, j))
}
}
}

let dirs = [-1, 0, 1, 0, -1]

while !queue.isEmpty {
let (i, j) = queue.removeFirst()
for d in 0..<4 {
let x = i + dirs[d]
let y = j + dirs[d + 1]
if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 {
ans[x][y] = ans[i][j] + 1
queue.append((x, y))
}
}
}

return ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
33 changes: 33 additions & 0 deletions lcof2/剑指 Offer II 107. 矩阵中的距离/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
func updateMatrix(_ mat: [[Int]]) -> [[Int]] {
let m = mat.count
let n = mat[0].count
var ans = Array(repeating: Array(repeating: -1, count: n), count: m)
var queue = [(Int, Int)]()

for i in 0..<m {
for j in 0..<n {
if mat[i][j] == 0 {
ans[i][j] = 0
queue.append((i, j))
}
}
}

let dirs = [-1, 0, 1, 0, -1]

while !queue.isEmpty {
let (i, j) = queue.removeFirst()
for d in 0..<4 {
let x = i + dirs[d]
let y = j + dirs[d + 1]
if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 {
ans[x][y] = ans[i][j] + 1
queue.append((x, y))
}
}
}

return ans
}
}
Loading