forked from satruddh/Hacktoberfest2k22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FloodFill.java
55 lines (51 loc) · 1.71 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
45
46
47
48
49
50
51
52
53
54
55
class FloodFill
{
private void dfs(int row, int col,
int[][] ans,
int[][] image,
int newColor, int delRow[], int delCol[],
int iniColor) {
// color with new color
ans[row][col] = newColor;
int n = image.length;
int m = image[0].length;
// there are exactly 4 neighbours
for(int i = 0;i<4;i++) {
int nrow = row + delRow[i];
int ncol = col + delCol[i];
// check for valid coordinate
// then check for same initial color and unvisited pixel
if(nrow>=0 && nrow<n && ncol>=0 && ncol < m &&
image[nrow][ncol] == iniColor && ans[nrow][ncol] != newColor) {
dfs(nrow, ncol, ans, image, newColor, delRow, delCol, iniColor);
}
}
}
public int[][] floodFill(int[][] image, int sr, int sc, int newColor)
{
// get initial color
int iniColor = image[sr][sc];
int[][] ans = image;
// delta row and delta column for neighbours
int delRow[] = {-1, 0, +1, 0};
int delCol[] = {0, +1, 0, -1};
dfs(sr, sc, ans, image, newColor, delRow, delCol, iniColor);
return ans;
}
public static void main(String[] args)
{
int[][] image = {
{1,1,1},
{1,1,0},
{1,0,1}
};
// sr = 1, sc = 1, newColor = 2
FloodFill obj = new FloodFill();
int[][] ans = obj.floodFill(image, 1, 1, 2);
for(int i = 0; i < ans.length; i++){
for(int j = 0; j < ans[i].length; j++)
System.out.print(ans[i][j] + " ");
System.out.println();
}
}
}