Skip to content

Commit 670a993

Browse files
authored
2022-07-11 update: added "Flood Fill" (#30)
1 parent 497ead9 commit 670a993

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
// https://leetcode.com/problems/flood-fill/
4+
public class FloodFill {
5+
6+
private final int[][] image;
7+
private final int sr;
8+
private final int sc;
9+
private final int color;
10+
11+
public FloodFill(int[][] image, int sr, int sc, int color) {
12+
this.image = image;
13+
this.sr = sr;
14+
this.sc = sc;
15+
this.color = color;
16+
}
17+
18+
public int[][] solution() {
19+
int c = image[sr][sc];
20+
if (c != color) {
21+
dfs(image, sr, sc, c, color);
22+
}
23+
return image;
24+
}
25+
26+
private void dfs(int[][] image, int r, int c, int color, int newColor) {
27+
if (image[r][c] == color) {
28+
image[r][c] = newColor;
29+
if (r >= 1) {
30+
dfs(image, r - 1, c, color, newColor);
31+
}
32+
if (c >= 1) {
33+
dfs(image, r, c - 1, color, newColor);
34+
}
35+
if (r + 1 < image.length) {
36+
dfs(image, r + 1, c, color, newColor);
37+
}
38+
if (c + 1 < image[0].length) {
39+
dfs(image, r, c + 1, color, newColor);
40+
}
41+
}
42+
}
43+
44+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.smlnskgmail.jaman.leetcodejava.easy;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertArrayEquals;
6+
import static org.junit.Assert.assertEquals;
7+
8+
public class FloodFillTest {
9+
10+
@Test
11+
public void defaultTest() {
12+
int[][] correct = new int[][]{{2, 2, 2}, {2, 2, 0}, {2, 0, 1}};
13+
int[][] solution = new FloodFill(
14+
new int[][]{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}},
15+
1,
16+
1,
17+
2
18+
).solution();
19+
assertEquals(correct.length, solution.length);
20+
for (int i = 0; i < correct.length; i++) {
21+
assertArrayEquals(correct[i], solution[i]);
22+
}
23+
}
24+
25+
}

0 commit comments

Comments
 (0)