用Java写一个实现平面求最短距离的两个点的代码,并且提现分治思想
时间: 2023-05-18 22:04:55 浏览: 118
好的,以下是一个用Java实现平面求最短距离的两个点的代码,同时也体现了分治思想:
```
import java.util.*;
public class ClosestPair {
static class Point {
double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
static class Pair {
Point p1, p2;
double distance;
public Pair(Point p1, Point p2, double distance) {
this.p1 = p1;
this.p2 = p2;
this.distance = distance;
}
}
public static Pair closestPair(Point[] points) {
Arrays.sort(points, (p1, p2) -> Double.compare(p1.x, p2.x));
return closestPair(points, 0, points.length - 1);
}
private static Pair closestPair(Point[] points, int left, int right) {
if (left >= right) {
return null;
}
int mid = (left + right) / 2;
Pair leftPair = closestPair(points, left, mid);
Pair rightPair = closestPair(points, mid + 1, right);
Pair minPair = min(leftPair, rightPair);
List<Point> strip = new ArrayList<>();
double midX = points[mid].x;
for (int i = left; i <= right; i++) {
if (Math.abs(points[i].x - midX) < minPair.distance) {
strip.add(points[i]);
}
}
strip.sort((p1, p2) -> Double.compare(p1.y, p2.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 < minPair.distance; j++) {
Pair pair = new Pair(strip.get(i), strip.get(j), distance(strip.get(i), strip.get(j)));
if (pair.distance < minPair.distance) {
minPair = pair;
}
}
}
return minPair;
}
private static Pair min(Pair p1, Pair p2) {
if (p1 == null) {
return p2;
}
if (p2 == null) {
return p1;
}
return p1.distance < p2.distance ? p1 : p2;
}
private static double distance(Point p1, Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
public static void main(String[] args) {
Point[] points = new Point[] { new Point(0, 0), new Point(1, 1), new Point(2, 2), new Point(3, 3) };
Pair pair = closestPair(points);
System.out.println(pair.distance);
}
}
```
这个算法的思想是:先按照x坐标排序,然后递归地将点集分成左右两部分,分别求出左右两部分的最近点对,然后取两部分中最近的点对作为当前区间的最近点对。接着,我们需要考虑两个点分别在左右两部分的情况,这时我们需要将点集按照y坐标排序,然后在中间的一段区间内暴力枚举所有点对,找到距离最近的点对。最后,我们将三种情况中距离最近的点对作为整个点集的最近点对。
希望这个代码能够帮到你!
阅读全文