我正在尝试用 C++ 实现格雷厄姆扫描,但它不起作用,我找不到原因。任何线索将不胜感激。经过一些尝试,我似乎总是有m_M = 2
,2分是最高的y分,如果有帮助的话。
交叉产品以了解它是右转还是左转。
qreal Interpolation::ccw(QPointF pt1, QPointF pt2, QPointF pt3)
{
return (pt2.x()-pt1.x())*(pt3.y()-pt1.y()) - (pt2.y()-pt1.y())*(pt3.x()-pt1.x());
}
点积除以范数得到 ,cos
因为排序的角度与排序的 相同cos in [0, Pi]
。
qreal Interpolation::dp(QPointF pt1, QPointF pt2)
{
return (pt2.x()-pt1.x())/qSqrt((pt2.x()-pt1.x())*(pt2.x()-pt1.x()) + (pt2.y()-pt1.y())*(pt2.y()-pt1.y()));
}
主要功能:
void Interpolation::ConvexHull()
{
QPointF points[m_N+1]; // My number of points
QPointF pt_temp(m_pt[0]);
qreal angle_temp(0);
int k_temp(0);
points[1]
用较低的 y 点填充数组点:
for (int i(1); i < m_N; ++i)
{
if (m_pt[i].y() < pt_temp.y())
{
points[i+1] = pt_temp;
pt_temp = m_pt[i];
}
else
{
points[i+1] = m_pt[i];
}
}
points[1] = pt_temp;
按角度对点数组进行排序并执行points[m_N] = points[0]
for (int i(2); i <= m_N; ++i)
{
pt_temp = points[i];
angle_temp = dp(points[1], pt_temp);
k_temp = i;
for (int j(1); j <= m_N-i; ++j)
{
if (dp(points[1], points[i+j]) < angle_temp)
{
pt_temp = points[i+j];
angle_temp = dp(points[1], points[i+j]);
k_temp = i+j;
}
}
points[k_temp] = points[i];
points[i] = pt_temp;
}
points[0] = points[m_N];
执行 Graham 扫描
m_M = 1; // Number of points on the convex hull.
for (int i(2); i <= m_N; ++i)
{
while (ccw(points[m_M-1], points[m_M], points[i]) <= 0)
{
if (m_M > 1)
{
m_M -= 1;
}
else if (i == m_N)
{
break;
}
else
{
i += 1;
}
}
m_M += 1;
pt_temp = points[m_M];
points[m_M] = points[i];
points[i] = points[m_M];
}
保存点m_convexHull
应该是船体上的点列表ConvexHull[m_M]=[ConvexHull[0]
for (int i(0); i < m_M; ++i)
{
m_convexHull.push_back(points[i+1]);
}
m_convexHull.push_back(points[1]);
}