The Wayback Machine - https://web.archive.org/web/20240823161812/https://www.geeksforgeeks.org/check-if-given-polygon-is-a-convex-polygon-or-not/
Open In App

Check if given polygon is a convex polygon or not

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
10.82%
874

Given a 2D array point[][] with each row of the form {X, Y}, representing the co-ordinates of a polygon in either clockwise or counterclockwise sequence, the task is to check if the polygon is a convex polygon or not. If found to be true, then print “Yes” . Otherwise, print “No”.

In a convex polygon, all interior angles are less than or equal to 180 degrees

Examples:

Input: arr[] = { (0, 0), (0, 1), (1, 1), (1, 0) } 
Output: Yes 
Explanation:

 
Since all interior angles of the polygon are less than 180 degrees. Therefore, the required output is Yes.

Input : arr[] = {(0, 0), (0, 10), (5, 5), (10, 10), (10, 0)} 
Output : No 
Explanation: 
 


Since all interior angles of the polygon are not less than 180 degrees. Therefore, the required output is No.

Approach: Follow the steps below to solve the problem:

  • Traverse the array and check if direction of cross product of any two adjacent sides of the polygon are same or not. If found to be true, then print “Yes”.
  • Otherwise, print “No”. 
     

Below is the implementation of the above approach:

C++
// C++ program to implement
// the above approach

#include <bits/stdc++.h>
using namespace std;

// Utility function to find cross product
// of two vectors
int CrossProduct(vector<vector<int> >& A)
{
    // Stores coefficient of X
    // direction of vector A[1]A[0]
    int X1 = (A[1][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[1]A[0]
    int Y1 = (A[1][1] - A[0][1]);

    // Stores coefficient of X
    // direction of vector A[2]A[0]
    int X2 = (A[2][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[2]A[0]
    int Y2 = (A[2][1] - A[0][1]);

    // Return cross product
    return (X1 * Y2 - Y1 * X2);
}

// Function to check if the polygon is
// convex polygon or not
bool isConvex(vector<vector<int> >& points)
{
    // Stores count of
    // edges in polygon
    int N = points.size();

    // Stores direction of cross product
    // of previous traversed edges
    int prev = 0;

    // Stores direction of cross product
    // of current traversed edges
    int curr = 0;

    // Traverse the array
    for (int i = 0; i < N; i++) {

        // Stores three adjacent edges
        // of the polygon
        vector<vector<int> > temp
            = { points[i],
                points[(i + 1) % N],
                points[(i + 2) % N] };

        // Update curr
        curr = CrossProduct(temp);

        // If curr is not equal to 0
        if (curr != 0) {

            // If direction of cross product of
            // all adjacent edges are not same
            if (curr * prev < 0) {
                return false;
            }
            else {
                // Update curr
                prev = curr;
            }
        }
    }
    return true;
}

// Driver code
int main()
{
    vector<vector<int> > points
        = { { 0, 0 }, { 0, 1 }, 
            { 1, 1 }, { 1, 0 } };

    if (isConvex(points)) {
        cout << "Yes"
             << "\n";
    }
    else {
        cout << "No"
             << "\n";
    }
}
Java
// Java program to implement
// the above approach
class GFG
{
  
// Utility function to find cross product
// of two vectors
static int CrossProduct(int A[][])
{
    // Stores coefficient of X
    // direction of vector A[1]A[0]
    int X1 = (A[1][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[1]A[0]
    int Y1 = (A[1][1] - A[0][1]);

    // Stores coefficient of X
    // direction of vector A[2]A[0]
    int X2 = (A[2][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[2]A[0]
    int Y2 = (A[2][1] - A[0][1]);

    // Return cross product
    return (X1 * Y2 - Y1 * X2);
}

// Function to check if the polygon is
// convex polygon or not
static boolean isConvex(int points[][])
{
    // Stores count of
    // edges in polygon
    int N = points.length;

    // Stores direction of cross product
    // of previous traversed edges
    int prev = 0;

    // Stores direction of cross product
    // of current traversed edges
    int curr = 0;

    // Traverse the array
    for (int i = 0; i < N; i++) {

        // Stores three adjacent edges
        // of the polygon
        int temp[][]= { points[i],
                points[(i + 1) % N],
                points[(i + 2) % N] };

        // Update curr
        curr = CrossProduct(temp);

        // If curr is not equal to 0
        if (curr != 0) {

            // If direction of cross product of
            // all adjacent edges are not same
            if (curr * prev < 0) {
                return false;
            }
            else {
                // Update curr
                prev = curr;
            }
        }
    }
    return true;
}

// Driver code
public static void main(String [] args)
{
    int points[][] = { { 0, 0 }, { 0, 1 }, 
            { 1, 1 }, { 1, 0 } };

    if (isConvex(points))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}

// This code is contributed by chitranayal
Python
# Python3 program to implement
# the above approach

# Utility function to find cross product
# of two vectors
def CrossProduct(A):
    
    # Stores coefficient of X
    # direction of vector A[1]A[0]
    X1 = (A[1][0] - A[0][0])

    # Stores coefficient of Y
    # direction of vector A[1]A[0]
    Y1 = (A[1][1] - A[0][1])

    # Stores coefficient of X
    # direction of vector A[2]A[0]
    X2 = (A[2][0] - A[0][0])

    # Stores coefficient of Y
    # direction of vector A[2]A[0]
    Y2 = (A[2][1] - A[0][1])

    # Return cross product
    return (X1 * Y2 - Y1 * X2)

# Function to check if the polygon is
# convex polygon or not
def isConvex(points):
    
    # Stores count of
    # edges in polygon
    N = len(points)

    # Stores direction of cross product
    # of previous traversed edges
    prev = 0

    # Stores direction of cross product
    # of current traversed edges
    curr = 0

    # Traverse the array
    for i in range(N):
        
        # Stores three adjacent edges
        # of the polygon
        temp = [points[i], points[(i + 1) % N], 
                           points[(i + 2) % N]]

        # Update curr
        curr = CrossProduct(temp)

        # If curr is not equal to 0
        if (curr != 0):
            
            # If direction of cross product of
            # all adjacent edges are not same
            if (curr * prev < 0):
                return False
            else:
                
                # Update curr
                prev = curr

    return True

# Driver code
if __name__ == '__main__':
    
    points = [ [ 0, 0 ], [ 0, 1 ], 
               [ 1, 1 ], [ 1, 0 ] ]

    if (isConvex(points)):
        print("Yes")
    else:
        print("No")

# This code is contributed by SURENDRA_GANGWAR
C#
// C# program to implement
// the above approach
using System;

class GFG
{
  
// Utility function to find cross product
// of two vectors
static int CrossProduct(int [,]A)
{
    // Stores coefficient of X
    // direction of vector A[1]A[0]
    int X1 = (A[1, 0] - A[0, 0]);

    // Stores coefficient of Y
    // direction of vector A[1]A[0]
    int Y1 = (A[1, 1] - A[0, 1]);

    // Stores coefficient of X
    // direction of vector A[2]A[0]
    int X2 = (A[2, 0] - A[0, 0]);

    // Stores coefficient of Y
    // direction of vector A[2]A[0]
    int Y2 = (A[2, 1] - A[0, 1]);

    // Return cross product
    return (X1 * Y2 - Y1 * X2);
}

// Function to check if the polygon is
// convex polygon or not
static bool isConvex(int [,]points)
{
    // Stores count of
    // edges in polygon
    int N = points.GetLength(0);

    // Stores direction of cross product
    // of previous traversed edges
    int prev = 0;

    // Stores direction of cross product
    // of current traversed edges
    int curr = 0;

    // Traverse the array
    for (int i = 0; i < N; i++) {

        // Stores three adjacent edges
        // of the polygon
        int []temp1 = GetRow(points, i);
        int []temp2 = GetRow(points, (i + 1) % N);
        int []temp3 = GetRow(points, (i + 2) % N);
        int [,]temp = new int[points.GetLength(0),points.GetLength(1)];
        temp = newTempIn(points, temp1, temp2, temp3);

        // Update curr
        curr = CrossProduct(temp);

        // If curr is not equal to 0
        if (curr != 0) {

            // If direction of cross product of
            // all adjacent edges are not same
            if (curr * prev < 0) {
                return false;
            }
            else {
                // Update curr
                prev = curr;
            }
        }
    }
    return true;
}
public static int[] GetRow(int[,] matrix, int row)
  {
    var rowLength = matrix.GetLength(1);
    var rowVector = new int[rowLength];

    for (var i = 0; i < rowLength; i++)
      rowVector[i] = matrix[row, i];

    return rowVector;
  }
    public static int[,] newTempIn(int[,] points, int []row1,int []row2, int []row3)
  {
    int [,]temp= new int[points.GetLength(0), points.GetLength(1)];

    for (var i = 0; i < row1.Length; i++){
          temp[0, i] = row1[i];
        temp[1, i] = row2[i];
        temp[2, i] = row3[i];
    } 
    return temp;
  }
    
    
// Driver code
public static void Main(String [] args)
{
    int [,]points = { { 0, 0 }, { 0, 1 }, 
            { 1, 1 }, { 1, 0 } };

    if (isConvex(points))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}

// This code is contributed by 29AjayKumar 
JavaScript
<script>

// JavaScript program to implement
// the above approach

  
// Utility function to find cross product
// of two vectors
function CrossProduct(A)
{
    // Stores coefficient of X
    // direction of vector A[1]A[0]
    var X1 = (A[1][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[1]A[0]
    var Y1 = (A[1][1] - A[0][1]);

    // Stores coefficient of X
    // direction of vector A[2]A[0]
    var X2 = (A[2][0] - A[0][0]);

    // Stores coefficient of Y
    // direction of vector A[2]A[0]
    var Y2 = (A[2][1] - A[0][1]);

    // Return cross product
    return (X1 * Y2 - Y1 * X2);
}

// Function to check if the polygon is
// convex polygon or not
function isConvex(points)
{
    // Stores count of
    // edges in polygon
    var N = points.length;

    // Stores direction of cross product
    // of previous traversed edges
    var prev = 0;

    // Stores direction of cross product
    // of current traversed edges
    var curr = 0;

    // Traverse the array
    for (i = 0; i < N; i++) {

        // Stores three adjacent edges
        // of the polygon
        var temp= [ points[i],
                points[(i + 1) % N],
                points[(i + 2) % N] ];

        // Update curr
        curr = CrossProduct(temp);

        // If curr is not equal to 0
        if (curr != 0) {

            // If direction of cross product of
            // all adjacent edges are not same
            if (curr * prev < 0) {
                return false;
            }
            else {
                // Update curr
                prev = curr;
            }
        }
    }
    return true;
}

// Driver code

var points = [ [ 0, 0 ], [ 0, 1 ], 
        [ 1, 1 ], [ 1, 0 ] ];

if (isConvex(points))
{
    document.write("Yes");
}
else
{
    document.write("No");
}


// This code is contributed by 29AjayKumar 

</script>

Output
Yes

Time Complexity: O(N) 
Auxiliary Space:O(1)



Previous Article
Next Article

Similar Reads

Check whether two convex regular polygon have same center or not
Given two positive integers N and M which denotes the sides of the convex regular polygon where N &lt; M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each vertex of the polygon. Examples: Input: N = 9, M =
3 min read
Dynamic Convex hull | Adding Points to an Existing Convex Hull
Given a convex hull, we need to add a given number of points to the convex hull and print the convex hull after every point addition. The points should be in anti-clockwise order after addition of every point. Examples: Input : Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4) Point to add : (100, 100) Output : New convex hull : (-1, 4) (0, 0) (3, -1)
15 min read
Check if the given point lies inside given N points of a Convex Polygon
Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4
15 min read
Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
Given a convex polygon with n+2 sides. The task is to calculate the number of ways in which triangles can be formed by connecting vertices with non-crossing line segments.Examples: Input: n = 1 Output: 1 It is already a triangle so it can only be formed in 1 way.Input: n = 2 Output: 2 It can be cut into 2 triangles by using either pair of opposite
5 min read
Find number of diagonals in n sided convex polygon
Given n &gt; 3, find number of diagonals in n sided convex polygon.According to Wikipedia, In geometry, a diagonal is a line segment joining two vertices of a polygon or polyhedron, when those vertices are not on the same edge. Informally, any sloping line is called diagonal. Examples :  Input : 5Output : 5Explanation: Five possible diagonals are :
3 min read
Check if image contour is convex or not in OpenCV Python
In this article we will see different ways to check if an image contour is convex or not with help of python OpenCV. Contour: Contours are continuous curves that represent the boundaries of an object in an image. In the field of computer vision and image processing, contours are used to detect and analyze the shape and structure of objects in image
4 min read
Perimeter of Convex hull for a given set of points
Given n 2-D points points[], the task is to find the perimeter of the convex hull for the set of points. A convex hull for a set of points is the smallest convex polygon that contains all the points. Examples: Input: points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: 12 Input: points[] = {{0, 2}, {2, 1}, {3, 1}, {3, 7}} Out
10 min read
Polygon with maximum sides that can be inscribed in an N-sided regular polygon
Given a regular polygon of N sides, the task is to find the maximum sided polygon that can be inscribed inside the given polygon by joining non-adjacent vertices. Print -1, if no such polygon exist. Examples: Input: N = 8Output: 4Explanation:At most a 4 sided polygon can be inscribed inside the given 8-sided polygon as shown below: Input: N = 3Outp
3 min read
Convex Hull | Monotone chain algorithm
Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) Examples: Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: (0, 0) (3, 0)
12 min read
Deleting points from Convex Hull
Given a fixed set of points. We need to find convex hull of given set. We also need to find convex hull when a point is removed from the set. Example: Initial Set of Points: (-2, 8) (-1, 2) (0, 1) (1, 0) (-3, 0) (-1, -9) (2, -6) (3, 0) (5, 3) (2, 5) Initial convex hull:- (-2, 8) (-3, 0) (-1, -9) (2, -6) (5, 3)Point to remove from the set : (-2, 8)F
15+ min read
Quickhull Algorithm for Convex Hull
Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not PossibleThere must be at least three points to form
14 min read
Convex Hull using Jarvis' Algorithm or Wrapping
Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it. We strongly recommend to see the following post first. How to check if two given line segments intersect?The idea of Jarvis's Algorithm is simple, we start from the leftmost point (or point with minimum x coordinate valu
14 min read
Convex Hull using Divide and Conquer Algorithm
In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computational geometry for several reasons: Collision detectio
15 min read
Convex Hull in Python
The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling. What is Convex Hull?The convex h
15+ min read
Quickhull for Convex hull in Python
Quickhull is an efficient algorithm used to find the convex hull of a set of points in a plane. It works by recursively dividing the point set into two subsets and finding the convex hull for each subset. Quickhull Algorithm for Convex hull:Base Case:If the set of points has 0 or 1 elements, it is already the convex hull.Find the Endpoints:Find the
3 min read
Convex Hull Algorithm
The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling. What is Convex Hull?The convex h
8 min read
Convex Hull using Graham Scan
Prerequisite: How to check if two given line segments intersect?Jarvis’s Algorithm A convex hull is the smallest convex polygon that contains a given set of points. It is a useful concept in computational geometry and has applications in various fields such as computer graphics, image processing, and collision detection. A convex polygon is a polyg
15+ min read
Tangents between two Convex Polygons
Given two convex polygons, we need to find the lower and upper tangents to these polygons. As shown in the figure below, [Tex]T_{RL}      [/Tex]and [Tex]T_{LR}      [/Tex]show upper and lower tangent respectively.  Examples:   Input : First Polygon : {(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)} Second Polygon : {(-1, 0), (0, 1), (1, 0), (0, -2)}.Output
15+ min read
Check if it is possible to create a polygon with a given angle
Given an angle [Tex]a [/Tex]where, [Tex]1\le a&lt; 180 [/Tex]. The task is to check whether it is possible to make a regular polygon with all of its interior angle equal to [Tex]a [/Tex]. If possible then print "YES", otherwise print "NO" (without quotes). Examples: Input: angle = 90 Output: YES Polygons with sides 4 is possible with angle 90 degre
4 min read
Check if it is possible to create a polygon with given n sides
Given an array arr[] that contains the lengths of n sides that may or may not form a polygon. The task is to determine whether it is possible to form a polygon with all the given sides. Print Yes if possible else print No.Examples: Input: arr[] = {2, 3, 4} Output: YesInput: arr[] = {3, 4, 9, 2} Output: No Approach: In order to create a polygon with
5 min read
Check if an N-sided Polygon is possible from N given angles
Given an array arr[] of N elements, where each element represents an angle(in degrees) of a polygon, the task is to check whether it is possible to make an N-sided polygon with all the given angles or not. If it is possible then print Yes else print No. Examples: Input: N = 3, arr[] = {60, 60, 60}Output: YesExplanation: There exists a triangle(i.e.
4 min read
How to check if a given point lies inside or outside a polygon?
Given a polygon and a point 'p', find if 'p' lies inside the polygon or not. The points lying on the border are considered inside. Examples: Recommended ProblemPlease solve it on PRACTICE first, before moving on to the solution Solve ProblemApproach: The idea to solve this problem is based on How to check if two given line segments intersect, and t
9 min read
Javascript Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Check if given Binary string follows then given condition or not
Given binary string str, the task is to check whether the given string follows the below condition or not: String starts with a '1'.Each '1' is followed by empty string(""), '1', or "00".Each "00" is followed by empty string(""), '1'. If the given string follows the above criteria then print "Valid String" else print "Invalid String".Examples: Inpu
10 min read
Queries to check if sweets of given type can be eaten on given day or not
Given two arrays A[ ] and B[ ] consisting of N integers, where Ai denotes the quantity of sweets of the ith type and Bi denotes the priority of the ith sweet (higher the value greater is the priority), and an integer K, which denotes maximum number of sweets that can be eaten in a day. Sweets of lower priority cannot be eaten before a sweet of high
13 min read
Check if a given pattern exists in a given string or not including wild cards * and .
Given two strings text and pattern of length M and N respectively, The task is to check if the pattern matches the text or not. If found to be true, then print "Yes". Otherwise, print "No". Note: pattern can include the characters '*' and 'â€Ē' '*' matches zero or more occurrences of character right before the current character'â€Ē' matches any signal
15+ min read
Python3 Program to Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
12 min read
Minimum area of a Polygon with three points given
Given three points of a regular polygon(n &gt; 3), find the minimum area of a regular polygon (all sides same) possible with the points given.Examples: Input : 0.00 0.00 1.00 1.00 0.00 1.00 Output : 1.00 By taking point (1.00, 0.00) square is formed of side 1.0 so area = 1.00 . One thing to note in question before we proceed is that the number of s
14 min read
Angle between 3 given vertices in a n-sided regular polygon
Given a n-sided regular polygon and three vertices a1, a2 and a3, the task is to find the angle suspended at vertex a1 by vertex a2 and vertex a3. Examples: Input: n = 6, a1 = 1, a2 = 2, a3 = 4 Output: 90 Input: n = 5, a1 = 1, a2 = 2, a3 = 5 Output: 36 Approach: The angle subtended by an edge on the center of n sided regular polygon is 360/n.The an
6 min read
three90RightbarBannerImg