c# - 顺时针排序点列表

标签 c# algorithm sorting geometry computational-geometry

我遇到了问题,不知道如何解决。

我正在尝试对点列表进行排序,以便所有点都形成一条路径。到目前为止,我所做的是计算列表中所有点的中心点,然后使用来自 this post 的代码。基于哪个进行排序。这是借用的代码片段:

public int Compare(Point3D pointA, Point3D pointB)
{
    if (pointA.X - CenterPoint.X >= 0 && pointB.X - CenterPoint.X < 0)
        return 1;
    if (pointA.X - CenterPoint.X < 0 && pointB.X - CenterPoint.X >= 0)
        return -1;

    if (pointA.X - CenterPoint.X == 0 && pointB.X - CenterPoint.X == 0)
    {
        if (pointA.Y - CenterPoint.Y >= 0 || pointB.Y - CenterPoint.Y >= 0)
           if (pointA.Y > pointB.Y)
               return 1;
            else return -1;
        if (pointB.Y > pointA.Y)
            return 1;
        else return -1;
    }

    // compute the cross product of vectors (CenterPoint -> a) x (CenterPoint -> b)
    double det = (pointA.X - CenterPoint.X)*(pointB.Y - CenterPoint.Y) -
                     (pointB.X - CenterPoint.X)*(pointA.Y - CenterPoint.Y);
    if (det < 0)
        return 1;
    if (det > 0)
        return -1;

    // points a and b are on the same line from the CenterPoint
    // check which point is closer to the CenterPoint
    double d1 = (pointA.X - CenterPoint.X)*(pointA.X - CenterPoint.X) +
                    (pointA.Y - CenterPoint.Y)*(pointA.Y - CenterPoint.Y);
    double d2 = (pointB.X - CenterPoint.X)*(pointB.X - CenterPoint.X) +
                    (pointB.Y - CenterPoint.Y)*(pointB.Y - CenterPoint.Y);
    if (d1 > d2)
        return 1;
    else return -1;
}

在某些情况下它工作正常但有时它会产生奇迹,请看附图,黑点是计算中心点:

Picture A, black dot is a center Point

在图 A 中一切正常,但是如果我决定向上移动形成两条水平线的点,我会遇到这个:

PictureB,black dot is a center Point

绿线是它应该的样子,黑线是它的真实样子,我不明白为什么我会这样。我还尝试了 atan() 解决方案,但结果相同。非常感谢任何帮助。

最佳答案

在您的两个示例中,点都按顺时针方向排序。但是对于第二个例子,它的方法不合适。顺时针算法仅适用于凸图形。

这里是不支持图形的示例,没有可用的中心点。

enter image description here

因此,如果您有一些点集,​​但不知道如何链接它们,并且对图形一无所知,您就无法恢复原始图形。

关于c# - 顺时针排序点列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336864/

相关文章:

c# - 如何在 Gridview 中仅对第一列使用 Rowspan

c# - 防止特定行在 Designer.cs 中自动更改代码

c# - Entity Framework 核心一对多,主表上没有外键

python - 按优先级对 Python 字典进行排序

algorithm - 使用二进制搜索的并行合并排序

c# - Parallel.For 循环的完整 CPU 使用率

algorithm - 针对一系列集合检查子集的高效算法

performance - 从包含键值对的字符串高效地创建数据框

java - 编写通用的二分查找方法

java - 使用第三列进行二维数组排序