Convex Polygon in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of points that form a polygon when joined sequentially, we have to find if this polygon is convex (Convex polygon definition). We have to keep in mind that there are at least 3 and at most 10,000 points. And the coordinates are in the range -10,000 to 10,000.

We can assume the polygon formed by given points is always a simple polygon, in other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other. So if the input is like: [[0,0],[0,1],[1,1],[1,0]], then it is convex, so returned value will be true.

To solve this, we will follow these steps −

  • Define a method calc(), this will take ax, ay, bx, by, cx, cy, this will work as follows −

  • BAx := ax – bx, BAy := ay – by, BCx := cx – bx, BCy := cy - by

  • From the main method do the following

  • neg := false and pos := false, n := size of points array

  • for i in range 0 to n – 1

    • a := i, b := (i + 1) mod n and c := (i + 2) mod n

    • cross_prod := calc(p[a, 0], p[a, 1], p[b, 0], p[b, 1], p[c, 0], p[c, 1])

    • if cross_prod < 0, then neg := true, otherwise when cross_prod > 0, then pos := true

    • if neg and pos is true, then return false

  • return true

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool isConvex(vector<vector<int>>& points) {
      bool neg = false;
      bool pos = false;
      int n = points.size();
      for(int i = 0; i < n; i++){
         int a = i;
         int b = (i + 1) % n;
         int c = (i + 2) % n;
         int crossProduct = calc(points[a][0], points[a][1], points[b][0], points[b][1], points[c][0], points[c][1]);
         if(crossProduct < 0) neg = true;
         else if(crossProduct > 0) pos = true;
         if(neg && pos) return false;
      }
      return true;
   }
   int calc(int ax, int ay, int bx, int by, int cx, int cy){
      int BAx = ax - bx;
      int BAy = ay - by;
      int BCx = cx - bx;
      int BCy = cy - by;
      return (BAx * BCy - BAy * BCx);
   }
};
main(){
   vector<vector<int>> v = {{0,0},{0,1},{1,1},{1,0}};
   Solution ob;
   cout << (ob.isConvex(v));
}

Input

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

Output

1
raja
Published on 31-Mar-2020 09:00:25
Advertisements