寻找平面点集中两点的最短距离

前言

本文主要呈现了用分治法求解“寻找平面点集中两点的最短距离”问题的代码。


问题分析

先将点集按x坐标排序,从中间分为两部分,每个子部分递归地找到最短距离,再考虑中间部分,从三者中选择最小的距离。
在考虑中间部分时,只需要考虑距离中线为d(子部分的最短距离)的点子集,将点子集按y坐标排序后只需要搜索O(1)的部分即可(因为在子集内同一边的每个点的间距不会小于d,只有分布在不同边的点的间距可能小于d。这个范围是常数的,最多看前后的一共10个点就够了)。

代码实现

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
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;

class Point
{
public:
Point(int x, int y) :x(x), y(y){}
int x;
int y;
friend ostream& operator <<(ostream& os, Point& p);
};
ostream& operator <<(ostream& os, Point& p)
{
os << "(" << p.x << "," << p.y << ")";
return os;
}
vector<Point> points{ Point(1, 3), Point(3,1), Point(4, 2), Point(1, 1), Point(6, 5),
Point(7, 2), Point(10, 2), Point(6,8), Point(2, 5), Point(6, 7) };
//为Point类的排序设置谓词
bool funx(Point p1, Point p2)
{
return p1.x < p2.x;
}
bool funy(Point p1, Point p2)
{
return p1.y < p2.y;
}
//点之间距离
double mydistance(Point p1, Point p2)
{
int diffx = p2.x - p1.x;
int diffy = p2.y - p1.y;
return sqrt(diffx*diffx+diffy*diffy);
}
double mindis(vector<Point> &points, int left, int right)
{
if (right == left)return 10000;
//一边只有一个点时,我们把距离设为一个大数,让其取决于另一边或中间部分。
if ((right - left) == 1) return mydistance(points[left], points[right]);
int mid = left + (right - left) / 2;
double lmin = mindis(points, left, mid);
double rmin = mindis(points, mid + 1, right);
double delta = min(lmin, rmin);
double res = delta;
vector<Point> subpoints;
for (int i = left; i <= right; i++)
{
if ((points[i].x - points[mid].x) < delta)subpoints.push_back(points[i]);
}
sort(subpoints.begin(), subpoints.end(), funy);
int sublen = subpoints.size();
for (int i = 0; i < sublen; i++)
{
for (int t = -7; t < 7; t++)//只考虑前后7个点
{
int k = i+t;
if (k < 0||k==i)continue;//边界情况,索引不能小于0或者为本身
if (k >= sublen)break;
else res = max(res, mydistance(subpoints[i], subpoints[k]));
}
}

return res;
}
int main(){
int len = points.size();
sort(points.begin(), points.end(), funx);
cout << mindis(points,0,len-1);
system("pause");
}
您的支持是我创造源源不断地动力