Skip to content

Commit 546980b

Browse files
authored
feat: add swift implementation to lcci problem: No.08.10 (doocs#2696)
1 parent bfcac26 commit 546980b

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

lcci/08.10.Color Fill/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,33 @@ impl Solution {
192192
}
193193
```
194194

195+
```swift
196+
class Solution {
197+
private var dirs = [-1, 0, 1, 0, -1]
198+
private var image: [[Int]] = []
199+
private var nc: Int = 0
200+
private var oc: Int = 0
201+
202+
func floodFill(_ image: inout [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] {
203+
self.nc = newColor
204+
self.oc = image[sr][sc]
205+
self.image = image
206+
dfs(sr, sc)
207+
return self.image
208+
}
209+
210+
private func dfs(_ i: Int, _ j: Int) {
211+
if i < 0 || i >= image.count || j < 0 || j >= image[0].count || image[i][j] != oc || image[i][j] == nc {
212+
return
213+
}
214+
image[i][j] = nc
215+
for k in 0..<4 {
216+
dfs(i + dirs[k], j + dirs[k + 1])
217+
}
218+
}
219+
}
220+
```
221+
195222
<!-- tabs:end -->
196223

197224
### 方法二:BFS

lcci/08.10.Color Fill/README_EN.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,33 @@ impl Solution {
199199
}
200200
```
201201

202+
```swift
203+
class Solution {
204+
private var dirs = [-1, 0, 1, 0, -1]
205+
private var image: [[Int]] = []
206+
private var nc: Int = 0
207+
private var oc: Int = 0
208+
209+
func floodFill(_ image: inout [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] {
210+
self.nc = newColor
211+
self.oc = image[sr][sc]
212+
self.image = image
213+
dfs(sr, sc)
214+
return self.image
215+
}
216+
217+
private func dfs(_ i: Int, _ j: Int) {
218+
if i < 0 || i >= image.count || j < 0 || j >= image[0].count || image[i][j] != oc || image[i][j] == nc {
219+
return
220+
}
221+
image[i][j] = nc
222+
for k in 0..<4 {
223+
dfs(i + dirs[k], j + dirs[k + 1])
224+
}
225+
}
226+
}
227+
```
228+
202229
<!-- tabs:end -->
203230

204231
### Solution 2: BFS

lcci/08.10.Color Fill/Solution.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
private var dirs = [-1, 0, 1, 0, -1]
3+
private var image: [[Int]] = []
4+
private var nc: Int = 0
5+
private var oc: Int = 0
6+
7+
func floodFill(_ image: inout [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] {
8+
self.nc = newColor
9+
self.oc = image[sr][sc]
10+
self.image = image
11+
dfs(sr, sc)
12+
return self.image
13+
}
14+
15+
private func dfs(_ i: Int, _ j: Int) {
16+
if i < 0 || i >= image.count || j < 0 || j >= image[0].count || image[i][j] != oc || image[i][j] == nc {
17+
return
18+
}
19+
image[i][j] = nc
20+
for k in 0..<4 {
21+
dfs(i + dirs[k], j + dirs[k + 1])
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)