-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloodFill_733.java
More file actions
76 lines (64 loc) · 2.63 KB
/
FloodFill_733.java
File metadata and controls
76 lines (64 loc) · 2.63 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.leetcode.problems.medium;
import com.geeksforgeeks.array.Rotate2DMatrix;
/**
* @author neeraj on 01/09/19
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class FloodFill_733 {
public static void main(String[] args) {
floodFill(new int[][]{
{1, 1, 1}, {1, 1, 0}, {1, 0, 1}
}, 1, 1, 2);
floodFill_version1(new int[][]{
{1, 1, 1}, {1, 1, 0}, {1, 0, 1}
}, 1, 1, 2);
floodFill(new int[][]{
{0, 0, 0}, {0, 1, 1}
}, 1, 1, 1);
}
public static int[][] floodFill_version1(int[][] image, int sr, int sc, int color) {
fillColor(image, sr, sc, color, image[sr][sc]);
return image;
}
private static void fillColor(int[][] image, int row, int col, int color, int originalColor) {
if (row < 0 || col < 0 || row >= image.length || col >= image[0].length || image[row][col] != originalColor)
return;
image[row][col] = color;
// Top
fillColor(image, row - 1, col, color, originalColor);
// Right
fillColor(image, row, col + 1, color, originalColor);
// Down
fillColor(image, row + 1, col, color, originalColor);
// Left
fillColor(image, row, col - 1, color, originalColor);
}
public static int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int initialColor = image[sr][sc];
boolean[][] visited = new boolean[image.length][image[0].length];
dfs(image, visited, sr, sc, newColor, initialColor);
Rotate2DMatrix.print2DArray(image);
return image;
}
public static void dfs(int[][] image, boolean[][] visited, int sr, int sc, int newColor, int initialColor) {
image[sr][sc] = newColor;
visited[sr][sc] = true;
if (isSafe(image, visited, sr - 1, sc, initialColor)) {
dfs(image, visited, sr - 1, sc, newColor, initialColor);
}
if (isSafe(image, visited, sr, sc + 1, initialColor)) {
dfs(image, visited, sr, sc + 1, newColor, initialColor);
}
if (isSafe(image, visited, sr + 1, sc, initialColor)) {
dfs(image, visited, sr + 1, sc, newColor, initialColor);
}
if (isSafe(image, visited, sr, sc - 1, initialColor)) {
dfs(image, visited, sr, sc - 1, newColor, initialColor);
}
}
public static boolean isSafe(int[][] image, boolean[][] visited, int sr, int sc, int initialColor) {
return sr >= 0 && sc >= 0 && sr < image.length && sc < image[0].length
&& image[sr][sc] == initialColor && visited[sr][sc] == false;
}
}