C++完成最近点对问题与opengl可视化
1. 问题描述
在二维平面中给定n个点,从这n个点中寻找距离最近的那一对。
2. 解题思路
- 暴力搜索BFS
- 分治算法
3. 分治法思想
将整个点集合按照x排序,然后取中间轴mid_x作为分割线。将问题分解成两个小规模的问题。一直分解下去,直至区域内只有一个点或两个点。
合并时,只需考虑中间区域是否有更短距离点即可,将位于中间区域的点按照y轴排序,而后对每个点,只需遍历后续的6个点即可,原理如下。
4. 代码部分
- BFS
double CClosestPoints::bf_distance(std::vector<CPoint2d>& points, CPoint2d& p1, CPoint2d& p2)
{
double min_d = RAND_MAX, d;
for (int i = 0; i < points.size(); i++)
{
for (int j = i + 1; j < points.size();j++) {
d = dist(points[i], points[j]);
if (d < min_d) {
min_d = d;
p1 = points[i];
p2 = points[j];
}
}
}
return min_d;
}
- DC分治
double CClosestPoints::dc_distance(std::vector<CPoint2d>& points, int begin, int end, CPoint2d& p1, CPoint2d& p2)
{
if (begin == end) return RAND_MAX; //如果只有一个点,则返回无穷大
if (begin + 1 == end) {
//只有两个点返回两点距离
p1 = points[begin];
p2 = points[end];
return dist(points[begin], points[end]);
}
int mid = (begin + end) / 2;
double mid_x = points[mid].get_x(); //X坐标中位数
CPoint2d a, b, c, d;
double min_d = RAND_MAX;
double dl = dc_distance(points, begin, mid, a, b); //递归划分左边
double dr = dc_distance(points, mid + 1, end, c, d); //递归划分右边
if (dl < dr) //min_d为左右区域各部分距离最小值
{
min_d = dl;
p1 = a;
p2 = b;
}
else
{
min_d = dr;
p1 = c;
p2 = d;
}
std::vector<CPoint2d> temp; //临时存储mid_x左右两边min_d范围内的点
for (int i = begin; i <= end; i++) {
if (fabs(points[i].get_x() - mid_x) <= min_d)
{
temp.emplace_back(points[i].get_x(), points[i].get_y());
}
}
std::sort(temp.begin(), temp.end(), sort_by_y); //按照y轴排序
for (int i = 0; i < temp.size(); i++)
{
for (int j = i + 1; j < temp.size() && j < i + 7; j++) {
double d = dist(temp[i], temp[j]);
if (d < min_d)
{
min_d = d;
p1 = temp[i];
p2 = temp[j];
}
}
}
return min_d;
}
5. opengl可视化