我正在尝试在C ++中实现Graham Scan,但它不起作用,我找不到原因。任何领导将不胜感激。经过一些尝试后,似乎我总是有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];
执行格雷厄姆扫描
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]);
}
答案 0 :(得分:9)
我发现了问题。它的句子在于:
点积除以范数得到cos,因为对角度进行排序与在[0,Pi]中对cos进行排序相同。
角度越低,cos越高,所以我只需更改这行代码:
if (dp(points[1], points[i+j]) < angle_temp)
到:
if (dp(points[1], points[i+j]) > angle_temp)
现在它完美无缺!