Skip to content

Commit b4a4d5e

Browse files
authored
feat: add swift implementation to lcof2 problem: No.107 (doocs#3620)
1 parent 28af7f8 commit b4a4d5e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

lcof2/剑指 Offer II 107. 矩阵中的距离/README.md

+38
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,44 @@ func updateMatrix(mat [][]int) [][]int {
200200
}
201201
```
202202

203+
#### Swift
204+
205+
```swift
206+
class Solution {
207+
func updateMatrix(_ mat: [[Int]]) -> [[Int]] {
208+
let m = mat.count
209+
let n = mat[0].count
210+
var ans = Array(repeating: Array(repeating: -1, count: n), count: m)
211+
var queue = [(Int, Int)]()
212+
213+
for i in 0..<m {
214+
for j in 0..<n {
215+
if mat[i][j] == 0 {
216+
ans[i][j] = 0
217+
queue.append((i, j))
218+
}
219+
}
220+
}
221+
222+
let dirs = [-1, 0, 1, 0, -1]
223+
224+
while !queue.isEmpty {
225+
let (i, j) = queue.removeFirst()
226+
for d in 0..<4 {
227+
let x = i + dirs[d]
228+
let y = j + dirs[d + 1]
229+
if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 {
230+
ans[x][y] = ans[i][j] + 1
231+
queue.append((x, y))
232+
}
233+
}
234+
}
235+
236+
return ans
237+
}
238+
}
239+
```
240+
203241
<!-- tabs:end -->
204242

205243
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
func updateMatrix(_ mat: [[Int]]) -> [[Int]] {
3+
let m = mat.count
4+
let n = mat[0].count
5+
var ans = Array(repeating: Array(repeating: -1, count: n), count: m)
6+
var queue = [(Int, Int)]()
7+
8+
for i in 0..<m {
9+
for j in 0..<n {
10+
if mat[i][j] == 0 {
11+
ans[i][j] = 0
12+
queue.append((i, j))
13+
}
14+
}
15+
}
16+
17+
let dirs = [-1, 0, 1, 0, -1]
18+
19+
while !queue.isEmpty {
20+
let (i, j) = queue.removeFirst()
21+
for d in 0..<4 {
22+
let x = i + dirs[d]
23+
let y = j + dirs[d + 1]
24+
if x >= 0 && x < m && y >= 0 && y < n && ans[x][y] == -1 {
25+
ans[x][y] = ans[i][j] + 1
26+
queue.append((x, y))
27+
}
28+
}
29+
}
30+
31+
return ans
32+
}
33+
}

0 commit comments

Comments
 (0)