寻找三点定位的经典算法是错误的?

时间:2017-10-15 20:28:29

标签: c++ algorithm geometry computational-geometry

这里可以引用算法(http://algs4.cs.princeton.edu/91primitives/)和此处(http://www.geeksforgeeks.org/orientation-3-ordered-points/),

尝试以下代码:p1 = {0,0},p2 = {4,4},p3 = {0,3}或p1 = {0,0},p2 = {4,4},p3 = {0,5},我认为两种情况都应该是时钟方式,但算法输出逆时针方式。

// A C++ program to find orientation of three points
#include <iostream>
using namespace std;

struct Point
{
    int x, y;
};

// To find orientation of ordered triplet (p1, p2, p3).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p1, Point p2, Point p3)
{
    // See 10th slides from following link for derivation
    // of the formula
    int val = (p2.y - p1.y) * (p3.x - p2.x) -
            (p2.x - p1.x) * (p3.y - p2.y);

    cout << val << endl;
    if (val == 0) return 0; // colinear

    return (val > 0)? 1: 2; // clock or counterclock wise
}

// Driver program to test above functions
int main()
{
    Point p1 = {0, 0}, p2 = {4, 4}, p3 = {0, 3};
    int o = orientation(p1, p2, p3);
    if (o==0)        cout << "Linear";
    else if (o == 1) cout << "Clockwise";
    else             cout << "CounterClockwise";
    return 0;
}

2 个答案:

答案 0 :(得分:1)

让我们绘制序列(0, 0) -> (4, 4) -> (0, 3)

enter image description here

如您所见,它是逆时针方向。因此代码工作正常,你只是在判断时犯了错误。

答案 1 :(得分:0)

顺时针或逆时针取决于您的轴方向!

真正重要的是三角形测试为对齐点提供0,一方为正,另一方为负。

只需拿一个测试用例,你就会永远知道什么是正确的&#34;签名&#34;。