-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloodfill.java
More file actions
38 lines (31 loc) · 1012 Bytes
/
Copy pathfloodfill.java
File metadata and controls
38 lines (31 loc) · 1012 Bytes
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
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
// base case
if (image[sr][sc] == color) {
return image;
}
int prevColor = image[sr][sc];
image[sr][sc] = color;
dfs(image, sr, sc, color, prevColor);
return image;
}
public void dfs(int[][] image, int sr, int sc, int color, int prevColor) {
int adjCells[][] = {
{ 0, 1 },
{ 1, 0 },
{ 0, -1 },
{ -1, 0 }
};
// dimensions of image to check bounds;
int imgrlen = image.length;
int imgclen = image[0].length;
for (int[] cellVal : adjCells) {
int r = sr + cellVal[0];
int c = sc + cellVal[1];
if (r < imgrlen && r >= 0 && c < imgclen && c >= 0 && image[r][c] == prevColor) {
image[r][c] = color;
dfs(image, r, c, color, prevColor);
}
}
}
}