-
Notifications
You must be signed in to change notification settings - Fork 0
/
0. Flood fill
104 lines (85 loc) · 2.86 KB
/
0. Flood fill
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
Given a matrix of integers,
return 2 numbers: integer - key, integer value,
where value is maximum area of an 'island' which consist of the same numbers - keys.
i.e.:
for matrix
1,2,2,3
1,1,2,3
1,2,2,3
2,1,1,1
answer will be 2 - 5
*/
public class Solution {
public int[] findMaxIsland(int[][] grid) {
boolean[][] isVisitedGrid = new boolean[grid.length][grid[0].length];
int maxCountKey = 0;
int maxCountValue = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (!isVisitedGrid[i][j]) {
int islandKey = grid[i][j];
int count = traverseIslandAndCountFields(islandKey, grid, isVisitedGrid, i, j);
if (count > maxCountValue) {
maxCountKey = islandKey;
maxCountValue = count;
}
}
}
}
return new int[]{maxCountKey, maxCountValue};
}
// breadth first search
private int traverseIslandAndCountFields(int value, int[][] grid, boolean[][] isVisitedGrid, int iInit, int jInit) {
int counter = 0;
ArrayDeque<Coordinate> queue = new ArrayDeque<>();
queue.addFirst(new Coordinate(iInit, jInit));
while (!queue.isEmpty()) {
Coordinate coordinate = queue.pollFirst();
int i = coordinate.i;
int j = coordinate.j;
if (!isVisitedGrid[i][j]) {
counter++;
isVisitedGrid[i][j] = true;
List.of(new Coordinate(i + 1, j),
new Coordinate(i - 1, j),
new Coordinate(i, j + 1),
new Coordinate(i, j - 1))
.stream()
.filter(c -> c.isNewLandOfCurrentIsland(value, grid, isVisitedGrid))
.forEach(queue::addLast);
}
}
return counter;
}
private static class Coordinate {
int i;
int j;
public Coordinate(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Coordinate that = (Coordinate) o;
return i == that.i &&
j == that.j;
}
boolean isNewLandOfCurrentIsland(int value, int[][] grid, boolean[][] isVisited) {
return i >= 0 && i < grid.length
&& j >= 0 && j < grid[i].length
&& grid[i][j] == value
&& !isVisited[i][j];
}
}
}