-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
37 lines (32 loc) · 1.46 KB
/
Solution.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
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
Map<String, Boolean> filledMap = new HashMap<String, Boolean>();
List<Integer[]> stack = new ArrayList<Integer[]>();
int color = image[sr][sc];
stack.add(new Integer[]{sr, sc});
while (stack.size() > 0) {
Integer[] point = stack.get(stack.size() - 1);
stack.remove(stack.size() - 1);
String coordinate = String.valueOf(point[0]) + "X" + String.valueOf(point[1]);
if (filledMap.get(coordinate) == null) {
filledMap.put(coordinate, true);
} else {
continue;
}
if (point[0] >= 1 && image[point[0] - 1][point[1]] == color) {
stack.add(new Integer[]{point[0] - 1, point[1]});
}
if (point[0] + 1 < image.length && image[point[0] + 1][point[1]] == color) {
stack.add(new Integer[]{point[0] + 1, point[1]});
}
if (point[1] >= 1 && image[point[0]][point[1] - 1] == color) {
stack.add(new Integer[]{point[0], point[1] - 1});
}
if (point[1] + 1 < image[0].length && image[point[0]][point[1] + 1] == color) {
stack.add(new Integer[]{point[0], point[1] + 1});
}
image[point[0]][point[1]] = newColor;
}
return image;
}
}