【发布时间】:2012-06-19 19:06:35
【问题描述】:
我正在尝试在 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]);
}
【问题讨论】:
-
Leo,请不要使用您自己找到的解决方案来编辑问题。如果您提出问题,然后自己找到答案,请将您的答案作为答案发布,并保持原始帖子不变。时间过去后,您可以接受自己的答案。
-
@JohnDibling 我听从了你的建议,并用正确的答案替换了编辑。
-
太好了,谢谢。现在,如果未来的 StackOverflow 用户搜索同样的问题,从解决方案中解析问题会更容易。几分钟后,您可以接受您的回答。我对 Q 和 A 都投了赞成票。享受代表。 :)
标签: c++ algorithm qt math computational-geometry