[LeetCode] Convex Polygon 凸多邊形


 

Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).

Note:

  1. There are at least 3 and at most 10,000 points.
  2. Coordinates are in the range -10,000 to 10,000.
  3. You may assume the polygon formed by given points is always a simple polygon (Simple polygon definition). In other words, we ensure that exactly two edges intersect at each vertex, and that edges otherwise don't intersect each other.

Example 1:

[[0,0],[0,1],[1,1],[1,0]]

Answer: True

Explanation:

Example 2:

[[0,0],[0,10],[10,10],[10,0],[5,5]]

Answer: False

Explanation:

 

這道題讓我們讓我們判斷一個多邊形是否為凸多邊形,我想關於凸多邊形的性質,我大天朝的初中幾何就應該有所涉獵啦吧,忘了的去面壁。就是所有的頂點角都不大於180度。那么我們該如何快速驗證這一個特點呢,學過計算機圖形學或者是圖像處理的課應該對計算法線normal並不陌生吧,計算的curve的法向量是非常重要的手段,一段連續曲線可以離散看成許多離散點組成,而相鄰的三個點就是最基本的單位,我們可以算由三個點組成的一小段曲線的法線方向,而凸多邊形的每個三個相鄰點的法向量方向都應該相同,要么同正,要么同負。那么我們只要遍歷每個點,然后取出其周圍的兩個點計算法線方向,然后跟之前的方向對比,如果不一樣,直接返回false。這里我們要特別注意法向量為0的情況,如果某一個點的法向量算出來為0,那么正確的pre就會被覆蓋為0,后面再遇到相反的法向就無法檢測出來,所以我們對計算出來法向量為0的情況直接跳過即可,參見代碼如下:

 

class Solution {
public:
    bool isConvex(vector<vector<int>>& points) {
        long long n = points.size(), pre = 0, cur = 0;
        for (int i = 0; i < n; ++i) {
            int dx1 = points[(i + 1) % n][0] - points[i][0];
            int dx2 = points[(i + 2) % n][0] - points[i][0];
            int dy1 = points[(i + 1) % n][1] - points[i][1];
            int dy2 = points[(i + 2) % n][1] - points[i][1];
            cur = dx1 * dy2 - dx2 * dy1;
            if (cur != 0) {
                if (cur * pre < 0) return false;
                else pre = cur;
            }
        }
        return true;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/70643/i-believe-this-time-it-s-far-beyond-my-ability-to-get-a-good-grade-of-the-contest

https://discuss.leetcode.com/topic/70664/c-7-line-o-n-solution-to-check-convexity-with-cross-product-of-adajcent-vectors-detailed-explanation/2

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

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



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