c++ - 如何判断一个多边形是凹的还是凸的?

标签 c++ algorithm geometry polygon coordinate-systems

用户输入第n个点。我需要检查多边形是否存在,然后确定类型 - 凹多边形或凸多边形。我知道如果每个角都在 180 度以下,则多边形是凸的。所以问题归结为找到多边形的每个内角。我一直在寻找公式或算法,但没有成功。

示例:

输入:n = 4;

第 1 点:(5;6)

点 2: (4;-5)

Point3: (-5;4)

第 4 点:(-5;5)

预期输出:多边形是凸的

Example

这是到目前为止的代码:现在它只找到平面中点之间的最大和最小距离。

#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    double a[15][2];
    int n;
    cin >> n;
    if (n <= 0 && n > 15)
        return 1;

    for (int i = 0; i < n; i++)
    {
        cout << "x" << i << " = , y" << i << " = ";
        cin >> a[i][0] >> a[i][1];
    }

    double maxDistance = 0.0;
    double minDistance = 0.0;
    double maxpoint1[2];
    double maxpoint2[2];
    double minpoint1[2];
    double minpoint2[2];

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (j != i)
            {
                double x1 = a[i][0];
                double x2 = a[j][0];
                double y1 = a[i][1];
                double y2 = a[j][1];
                double currentDistance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));

                if (currentDistance > maxDistance)
                {
                    maxDistance = currentDistance;
                    maxpoint1[0] = x1;
                    maxpoint1[1] = y1;
                    maxpoint2[0] = x2;
                    maxpoint2[1] = y2;

                }

                if (minDistance > currentDistance)
                {
                    currentDistance = minDistance;
                    minpoint1[0] = x1;
                    minpoint1[1] = y1;
                    minpoint2[0] = x2;
                    minpoint2[1] = y2;
                }

                cout << "x1 = " << x1 << " y1 = " << y1 << " x2 = " << x2 << " y2 = " << y2;
                cout << endl << "Distance is " << currentDistance;
                cout << endl;
            }
        }
    }

    cout << "The max distance is: " << maxDistance << " between x1 = " << maxpoint1[0] << " y1 = " << maxpoint1[1] << " and x2 = " << maxpoint2[0] << " y2 = " << maxpoint2[1];
    cout << "The min distance is: " << minDistance << " between x1 = " << minpoint1[0] << " y1 = " << minpoint1[1] << " and x2 = " << minpoint2[0] << " y2 = " << minpoint2[1];


    return 0;
}

最佳答案

要确定多边形是凸面还是凹面,只需检查所有连续点三元组的叉积符号 CrossProduct(P[0], P[1], P[2]) 等。例如

CrossProductSign(A, B, C) = 
               SignOf((B.X - A.X) * (C.Y - B.Y) - (B.Y - A.Y) * (C.X - B.X))

对于凸一,所有叉积必须具有相同的符号(+ 或 -)。

工作原理:对于凸多边形,每个三元组都在同一侧转弯(或顺时针或逆时针,具体取决于行走方向)。对于凹形,一些标志会有所不同(内角超过 180 度)。请注意,您不需要计算角度值。

关于c++ - 如何判断一个多边形是凹的还是凸的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40738013/

相关文章:

algorithm - 创建多个组合,总和为 100

java - 为给定的一组路点或一条线绘制多边形?

Swift Animation - 后面有圆圈的按钮

java - 求封闭 GeneralPath 所包围的区域

c++ - 如何在约束delaunay三角剖分中获取三角形的顶点?

c++ - g++如何在忽略函数返回值时获得警告

algorithm - 从段落中找出问题的答案

c++ - 结构阵列奇数/偶数故障

c++ - 通过NULL类指针调用类方法

algorithm - 为什么过度拟合给出了错误的假设函数