-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRiverSizes.java
More file actions
62 lines (59 loc) · 1.58 KB
/
RiverSizes.java
File metadata and controls
62 lines (59 loc) · 1.58 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
import java.util.*;
class Program {
// O(hw) time | O(hw) space
public static List<Integer> riverSizes(int[][] matrix) {
// Write your code here.
List<Integer> riverSizes = new ArrayList<>();
int h = matrix.length;
int w = matrix[0].length;
boolean[][] visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (visited[i][j]) {
continue;
}
traverse(i, j, matrix, visited, riverSizes);
}
}
return riverSizes;
}
private static void traverse(int i, int j, int[][] matrix, boolean[][] visited, List<Integer> riverSizes) {
int riverSize = 0;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] { i, j });
while (!queue.isEmpty()) {
int[] position = queue.poll();
i = position[0];
j = position[1];
if (visited[i][j]) {
continue;
}
visited[i][j] = true;
if (matrix[i][j] == 0) {
continue;
}
++riverSize;
List<int[]> neighbors = getNeighbors(i, j, matrix, visited);
queue.addAll(neighbors);
}
if (riverSize > 0) {
riverSizes.add(riverSize);
}
}
private static List<int[]> getNeighbors(int i, int j, int[][] matrix, boolean[][] visited) {
List<int[]> neighbors = new ArrayList<>();
if (i > 0 && !visited[i - 1][j]) {
neighbors.add(new int[] { i - 1, j });
}
if (i < matrix.length - 1 && !visited[i + 1][j]) {
neighbors.add(new int[] { i + 1, j });
}
if (j > 0 && !visited[i][j - 1]) {
neighbors.add(new int[] { i, j - 1 });
}
if (j < matrix[0].length - 1 && !visited[i][j + 1]) {
neighbors.add(new int[] { i, j + 1 });
}
return neighbors;
}
}