Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).
Note:
- There are at least 3 and at most 10,000 points.
- Coordinates are in the range -10,000 to 10,000.
- 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; } };
參考資料: