判斷一個多邊形是順時針還是逆時針的方法


1、關於如何判定多邊形是順時針還是逆時針對於凸多邊形而言,只需對某一個點計算叉積 = ((xi - xi-1),(yi - yi-1)) x ((xi+1 - xi),(yi+1 - yi)) = (xi - xi-1) * (yi+1 - yi) - (yi - yi-1) * (xi+1 - xi)
如果上式的值為正,逆時針;為負則是順時針。

而對於一般的簡單多邊形,則需對於多邊形的每一個點計算上述值,如果正值比較多,是逆時針;負值較多則為順時針。

2、還有一種說明是取多邊形的極點值,多邊形的方向和這個頂點與其相鄰兩邊構成的方向相同。

需要注意的是在屏幕坐標中,Y是向下的,所以在屏幕坐標系中看到的順時針既是在Y軸向上的直角坐標系中看到的逆時針方向。

1.凸包的時候,只要判斷前三個點即可,計算叉積,判斷方向

2.凹包情況就復雜了,可以從三個方面考慮

首先,可以去凸包上的特殊點,x最大最小的點,y最大最小的點,這些極值點肯定是在凸包上的,可以計算這些的叉積,其次,直接統計叉積正負的數量,正多負少,是逆時針,反之,順時針。

一個簡單的做法是,計算面積,用面積的正負判斷方向。

【面積判斷法】

#include<cstdio>
#include<string>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<queue>
#include<algorithm>
#include<vector>
#include<map>
#include<cctype>
#include<stack>
#include<sstream>
#include<list>
#include<assert.h>
#include<bitset>
#include<numeric>
#define debug() puts("++++")
#define gcd(a,b) __gcd(a,b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a,b,sizeof(a))
#define sz size()
#define be begin()
#define pu push_up
#define pd push_down
#define cl clear()
#define lowbit(x) -x&x
#define all 1,n,1
#define mod 2000000000000000003
#define rep(i,n,x) for(int i=(x); i<(n); i++)
#define in freopen("in.in","r",stdin)
#define out freopen("out.out","w",stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 1e18;
const int MAXN =  1e3 + 5;
const int maxm = 1e6 + 10;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int dx[] = {-1,1,0,0,1,1,-1,-1};
const int dy[] = {0,0,1,-1,1,-1,1,-1};
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int maxn = 200050;


struct Point{
    double x, y;
};
double cross(Point a,Point b,Point c) {
    return (a.x-c.x)*(b.y-c.y)-(b.x-c.x)*(a.y-c.y);
}
//計算多邊形面積
double PolygonArea(Point p[], int n)
{
    if(n < 3) return 0.0;
    double s = p[0].y * (p[n - 1].x - p[1].x);
    p[n] = p[0];
    for(int i = 1; i < n; ++ i)
        s += p[i].y * (p[i - 1].x - p[i + 1].x);
    return s * 0.5;
}
Point p1[maxn];
int n1;
int main()
{
    while(scanf("%d",&n1) != EOF ){
        for(int i = 0; i < n1; i++)
            scanf("%lf%lf", &p1[i].x, &p1[i].y);
        if ( PolygonArea(p1,n1) > 0 )
            puts("counterclockwise");
        else
            puts("clockwise");
    }
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM