Skip to content

Commit 017287e

Browse files
committed
feat: add lcci color fill java solution
1 parent 96ad384 commit 017287e

File tree

3 files changed

+69
-2
lines changed

3 files changed

+69
-2
lines changed

lcci/08.10.Color Fill/README.md

+23-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,29 @@ sr = 1, sc = 1, newColor = 2
4242
<!-- 这里可写当前语言的特殊实现逻辑 -->
4343

4444
```java
45-
45+
class Solution {
46+
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
47+
int oldColor = image[sr][sc];
48+
dfs(image, sr, sc, oldColor, newColor);
49+
return image;
50+
}
51+
52+
private void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) {
53+
if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) {
54+
return;
55+
}
56+
57+
int color = image[sr][sc];
58+
if (color != newColor && color == oldColor) {
59+
image[sr][sc] = newColor;
60+
// up down left right
61+
dfs(image, sr, sc + 1, oldColor, newColor);
62+
dfs(image, sr, sc - 1, oldColor, newColor);
63+
dfs(image, sr + 1, sc, oldColor, newColor);
64+
dfs(image, sr - 1, sc, oldColor, newColor);
65+
}
66+
}
67+
}
4668
```
4769

4870
### ...

lcci/08.10.Color Fill/README_EN.md

+23-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,29 @@ to the starting pixel.</pre>
5656
### Java
5757

5858
```java
59-
59+
class Solution {
60+
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
61+
int oldColor = image[sr][sc];
62+
dfs(image, sr, sc, oldColor, newColor);
63+
return image;
64+
}
65+
66+
private void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) {
67+
if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) {
68+
return;
69+
}
70+
71+
int color = image[sr][sc];
72+
if (color != newColor && color == oldColor) {
73+
image[sr][sc] = newColor;
74+
// up down left right
75+
dfs(image, sr, sc + 1, oldColor, newColor);
76+
dfs(image, sr, sc - 1, oldColor, newColor);
77+
dfs(image, sr + 1, sc, oldColor, newColor);
78+
dfs(image, sr - 1, sc, oldColor, newColor);
79+
}
80+
}
81+
}
6082
```
6183

6284
### ...

lcci/08.10.Color Fill/Solution.java

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
3+
int oldColor = image[sr][sc];
4+
dfs(image, sr, sc, oldColor, newColor);
5+
return image;
6+
}
7+
8+
private void dfs(int[][] image, int sr, int sc, int oldColor, int newColor) {
9+
if (sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length) {
10+
return;
11+
}
12+
13+
int color = image[sr][sc];
14+
if (color != newColor && color == oldColor) {
15+
image[sr][sc] = newColor;
16+
// up down left right
17+
dfs(image, sr, sc + 1, oldColor, newColor);
18+
dfs(image, sr, sc - 1, oldColor, newColor);
19+
dfs(image, sr + 1, sc, oldColor, newColor);
20+
dfs(image, sr - 1, sc, oldColor, newColor);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)