-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path733.java
More file actions
80 lines (76 loc) · 2.24 KB
/
733.java
File metadata and controls
80 lines (76 loc) · 2.24 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
77
78
79
80
import java.util.*;
class Solution {
ArrayList<int[]> nextCoords;
public Solution(){
nextCoords = new ArrayList<int[]>();
}
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
int oldColor = image[sr][sc];
Queue<int[]> q = new LinkedList();
int[] first = {sr,sc};
q.add(first);
ArrayList<int[]> visited = new ArrayList<int[]>();
while (!q.isEmpty()){
int[] coords = q.remove();
visited.add(coords);
image = oneCycle(image,coords[0],coords[1],color,oldColor);
for (int[] coor : nextCoords){
// CHECK FOR VISITED BEFORE ADDING
if (!contains(visited, coor)){
q.add(coor);
}
}
nextCoords.clear();
visited.add(coords);
}
return image;
}
public boolean contains(ArrayList<int[]> visited, int[] checking){
for (int[] element : visited){
if ((element[0] == checking[0] && element[1] == checking[1])){
return true;
}
}
return false;
}
public int[][] oneCycle(int[][] image, int sr, int sc, int newColor, int origColor){
image[sr][sc] = newColor;
try{
if (image[sr+1][sc] == origColor){
image[sr+1][sc] = newColor;
int[] temp = {sr+1,sc};
nextCoords.add(temp);
}
}
catch(Exception e){
}
try{
if (image[sr-1][sc] == origColor){
image[sr-1][sc] = newColor;
int[] temp = {sr-1,sc};
nextCoords.add(temp);
}
}
catch(Exception e){
}
try{
if (image[sr][sc+1] == origColor){
image[sr][sc+1] = newColor;
int[] temp = {sr,sc+1};
nextCoords.add(temp);
}
}
catch(Exception e){
}
try{
if (image[sr][sc-1] == origColor){
image[sr][sc-1] = newColor;
int[] temp = {sr,sc-1};
nextCoords.add(temp);
}
}
catch(Exception e){
}
return image;
}
}