Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check whether two convex regular polygon have same center or not
Next article icon

Check if given polygon is a convex polygon or not

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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)



Next Article
Check whether two convex regular polygon have same center or not
author
mukulsomukesh
Improve
Article Tags :
  • DSA
  • Geometric
  • Mathematical
  • Python
  • Geometric-Lines
  • Maths
Practice Tags :
  • Geometric
  • Mathematical
  • python

Similar Reads

  • 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
    8 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 computationa
    15 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 leftm
    14 min read
  • Convex Hull using Graham Scan
    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 polygon in which all interior angles a
    15+ 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,
    12 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 P
    14 min read
  • Problems on Convex Hull

    • 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)
      15 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,
      15+ 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 Inpu
      10 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
      15 min read

    • Tangents between two Convex Polygons
      Given two convex polygons, we aim to identify the lower and upper tangents connecting them. As shown in the figure below, TRL and TLR represent the upper and lower tangents, respectively. Examples: Input: First Polygon : [[2, 2], [3, 3], [5, 2], [4, 0], [3, 1]] Second Polygon : [[-1, 0], [0, 1], [1,
      15+ min read

    • Check if given polygon is a convex polygon or not
      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
      9 min read

    • 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 < 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
      3 min read

    • Minimum Enclosing Circle
      Prerequisites: Equation of circle when three points on the circle are given, Convex HullGiven an array arr[][] containing N points in a 2-D plane with integer coordinates. The task is to find the centre and the radius of the minimum enclosing circle(MEC). A minimum enclosing circle is a circle in wh
      15+ min read

  • How to Highlight Groups with Convex Hull in ggplot2 in R?
    In this article, we are going to see how to highlight groups with the convex hull in ggplot2 using R Programming Language.  Convex hull polygon refers to the draw a line bounding box around the outermost points in each group. Creating scatterplot for demonstration Here we will use the iris dataset t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences