-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflood-fill.go
47 lines (37 loc) · 938 Bytes
/
flood-fill.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import "fmt"
// source: https://leetcode.com/problems/flood-fill/
func floodFill(image [][]int, sr int, sc int, color int) [][]int {
oldCol := image[sr][sc]
if oldCol == color {
return image
}
mr, mc := len(image), len(image[0])
var dfs func(r, c int)
dfs = func(r, c int) {
if r < 0 || r >= mr || c < 0 || c >= mc || image[r][c] != oldCol {
return
}
image[r][c] = color
dfs(r+1, c)
dfs(r-1, c)
dfs(r, c+1)
dfs(r, c-1)
}
dfs(sr, sc)
return image
}
func main() {
// Example 1
var image1 = [][]int{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}
var sr1 int = 1
var sc1 int = 1
var color1 int = 2
fmt.Println("Expected: [[2,2,2],[2,2,0],[2,0,1]] Output: ", floodFill(image1, sr1, sc1, color1))
// Example 2
var image2 = [][]int{{0, 0, 0}, {0, 0, 0}}
var sr2 int = 0
var sc2 int = 0
var color2 int = 0
fmt.Println("Expected: [[0,0,0],[0,0,0]] Output: ", floodFill(image2, sr2, sc2, color2))
}