-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosestpair
More file actions
65 lines (51 loc) · 1.75 KB
/
Copy pathclosestpair
File metadata and controls
65 lines (51 loc) · 1.75 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
import java.util.*;
class CPPoint {
int x, y;
CPPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
public class ClosestPair {
static double dist(CPPoint a, CPPoint b) {
return Math.sqrt(Math.pow(a.x - b.x, 2) +
Math.pow(a.y - b.y, 2));
}
static double bruteForce(CPPoint[] pts, int n) {
double min = Double.MAX_VALUE;
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
min = Math.min(min, dist(pts[i], pts[j]));
return min;
}
static double stripClosest(List<CPPoint> strip, double d) {
double min = d;
strip.sort(Comparator.comparingInt(p -> p.y));
for (int i = 0; i < strip.size(); i++) {
for (int j = i+1; j < strip.size() &&
(strip.get(j).y - strip.get(i).y) < min; j++) {
min = Math.min(min, dist(strip.get(i), strip.get(j)));
}
}
return min;
}
static double closestUtil(CPPoint[] pts, int n) {
if (n <= 3) return bruteForce(pts, n);
int mid = n / 2;
CPPoint midPoint = pts[mid];
CPPoint[] left = Arrays.copyOfRange(pts, 0, mid);
CPPoint[] right = Arrays.copyOfRange(pts, mid, n);
double dl = closestUtil(left, mid);
double dr = closestUtil(right, n - mid);
double d = Math.min(dl, dr);
List<CPPoint> strip = new ArrayList<>();
for (CPPoint p : pts)
if (Math.abs(p.x - midPoint.x) < d)
strip.add(p);
return Math.min(d, stripClosest(strip, d));
}
public static double closest(CPPoint[] pts) {
Arrays.sort(pts, Comparator.comparingInt(p -> p.x));
return closestUtil(pts, pts.length);
}
}