-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFloodFill.java
44 lines (38 loc) · 1.13 KB
/
FloodFill.java
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
package com.smlnskgmail.jaman.leetcodejava.easy;
// https://leetcode.com/problems/flood-fill/
public class FloodFill {
private final int[][] image;
private final int sr;
private final int sc;
private final int color;
public FloodFill(int[][] image, int sr, int sc, int color) {
this.image = image;
this.sr = sr;
this.sc = sc;
this.color = color;
}
public int[][] solution() {
int c = image[sr][sc];
if (c != color) {
dfs(image, sr, sc, c, color);
}
return image;
}
private void dfs(int[][] image, int r, int c, int color, int newColor) {
if (image[r][c] == color) {
image[r][c] = newColor;
if (r >= 1) {
dfs(image, r - 1, c, color, newColor);
}
if (c >= 1) {
dfs(image, r, c - 1, color, newColor);
}
if (r + 1 < image.length) {
dfs(image, r + 1, c, color, newColor);
}
if (c + 1 < image[0].length) {
dfs(image, r, c + 1, color, newColor);
}
}
}
}