forked from lee2018jian/airbnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberofIntersectedRectangles
45 lines (39 loc) · 1.51 KB
/
NumberofIntersectedRectangles
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
import java.util.Set;
public class NumberofIntersectedRectangles {
public class Solution {
private boolean intersect(int[][] r1, int[][] r2) {
return r1[0][0] < r2[0][0] && r1[0][1] < r2[0][1] && r2[0][0] < r1[1][0] && r2[0][1] < r1[1][1] ||
r1[0][0] < r2[1][0] && r1[0][1] < r2[1][1] && r2[1][0] < r1[1][0] && r2[1][1] < r1[1][1];
}
private int find(int val, int[] parents) {
while (parents[val] != val) {
val = parents[val];
}
return val;
}
public int countIntersection(int[][][] rectangles) {
if (rectangles == null || rectangles.length == 0) return 0;
int n = rectangles.length;
int[] parents = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (intersect(rectangles[i], rectangles[j])) {
int root1 = find(i, parents);
int root2 = find(j, parents);
if (root1 != root2) {
parents[root1] = root2;
}
}
}
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
set.add(find(i, parents));
}
return set.size();
}
}
}