Skip to content

Commit fd87f29

Browse files
committed
add scala solution for Flood-Fill
1 parent 6975de9 commit fd87f29

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
object Solution {
2+
def floodFill(image: Array[Array[Int]], sr: Int, sc: Int, newColor: Int): Array[Array[Int]] = {
3+
fill(image, sr, sc, image(sr)(sc), newColor)
4+
image
5+
}
6+
7+
def fill(image: Array[Array[Int]], r: Int, c: Int, startColor: Int, newColor: Int): Unit = {
8+
val oldColor = image(r)(c)
9+
if (oldColor == startColor && oldColor != newColor) {
10+
image(r)(c) = newColor
11+
if (r - 1 >= 0) fill(image, r - 1, c, startColor, newColor)
12+
if (c - 1 >= 0) fill(image, r, c - 1, startColor, newColor)
13+
if (r + 1 < image.length) fill(image, r + 1, c, startColor, newColor)
14+
if (c + 1 < image(0).length) fill(image, r, c + 1, startColor, newColor)
15+
}
16+
}
17+
}
18+
19+
20+
object Solution2 {
21+
def floodFill(image: Array[Array[Int]], sr: Int, sc: Int, newColor: Int): Array[Array[Int]] = {
22+
val startColor = image(sr)(sc)
23+
24+
def fill(r: Int, c: Int): Unit = {
25+
val oldColor = image(r)(c)
26+
if (oldColor == startColor && oldColor != newColor) {
27+
image(r)(c) = newColor
28+
if (r - 1 >= 0) fill(r - 1, c)
29+
if (c - 1 >= 0) fill(r, c - 1)
30+
if (r + 1 < image.length) fill(r + 1, c)
31+
if (c + 1 < image(0).length) fill(r, c + 1)
32+
}
33+
}
34+
35+
fill(sr, sc)
36+
image
37+
}
38+
}
39+

0 commit comments

Comments
 (0)