Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Geometric Algorithms
  • Basic Geometry
  • Computational Geometry
  • Slope of Line
  • Point of Intersection of Two Lines
  • Closest Pair of Points
  • Convex Hull
  • Pythagorean Quadruple
  • Polygon Triangulation
Open In App
Next Article:
Check if the given point lies inside given N points of a Convex Polygon
Next article icon

Perimeter of Convex hull for a given set of points

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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}} Output: 15.067

Approach: Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the clockwise direction and find the lower hull. We will then find the perimeter of the convex hull using the points on the convex hull which can be done in O(n) time as the points are already sorted in clockwise order. Below is the implementation of the above approach: 

CPP
// C++ implementation of the approach #include <bits/stdc++.h> #define llu long long int using namespace std;  struct Point {      llu x, y;      bool operator<(Point p)     {         return x < p.x || (x == p.x && y < p.y);     } };  // Cross product of two vectors OA and OB // returns positive for counter clockwise // turn and negative for clockwise turn llu cross_product(Point O, Point A, Point B) {     return (A.x - O.x) * (B.y - O.y)         - (A.y - O.y) * (B.x - O.x); }  // Returns a list of points on the convex hull // in counter-clockwise order vector<Point> convex_hull(vector<Point> A) {     int n = A.size(), k = 0;      if (n <= 3)         return A;      vector<Point> ans(2 * n);      // Sort points lexicographically     sort(A.begin(), A.end());      // Build lower hull     for (int i = 0; i < n; ++i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]         // and ans[k-2] to A[i] has a clockwise turn         while (k >= 2             && cross_product(ans[k - 2],                              ans[k - 1], A[i]) <= 0)             k--;         ans[k++] = A[i];     }      // Build upper hull     for (size_t i = n - 1, t = k + 1; i > 0; --i) {          // If the point at K-1 position is not a part         // of hull as vector from ans[k-2] to ans[k-1]         // and ans[k-2] to A[i] has a clockwise turn         while (k >= t             && cross_product(ans[k - 2],                          ans[k - 1], A[i - 1]) <= 0)             k--;         ans[k++] = A[i - 1];     }      // Resize the array to desired size     ans.resize(k - 1);      return ans; }  // Function to return the distance between two points double dist(Point a, Point b) {     return sqrt((a.x - b.x) * (a.x - b.x)                 + (a.y - b.y) * (a.y - b.y)); }  // Function to return the perimeter of the convex hull double perimeter(vector<Point> ans) {     double perimeter = 0.0;      // Find the distance between adjacent points     for (int i = 0; i < ans.size() - 1; i++) {         perimeter += dist(ans[i], ans[i + 1]);     }      // Add the distance between first and last point     perimeter += dist(ans[0], ans[ans.size() - 1]);      return perimeter; }  // Driver code int main() {     vector<Point> points;      // Add points     points.push_back({ 0, 3 });     points.push_back({ 2, 2 });     points.push_back({ 1, 1 });     points.push_back({ 2, 1 });     points.push_back({ 3, 0 });     points.push_back({ 0, 0 });     points.push_back({ 3, 3 });      // Find the convex hull     vector<Point> ans = convex_hull(points);      // Find the perimeter of convex polygon     cout << perimeter(ans);      return 0; } 
Java
import java.util.*; import java.lang.*; import java.io.*;  class Point {     int x, y;     Point(int x, int y) {         this.x = x;         this.y = y;     } }  class Main {     static int cross_product(Point o, Point a, Point b) {         return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);     }      static List<Point> convex_hull(List<Point> points) {         int n = points.size();         if (n <= 3)             return points;          Collections.sort(points, new Comparator<Point>() {             @Override             public int compare(Point p1, Point p2) {                 if (p1.x == p2.x)                     return p1.y - p2.y;                 return p1.x - p2.x;             }         });          Point[] ans = new Point[2 * n];         int k = 0;          // Build lower hull         for (int i = 0; i < n; i++) {             while (k >= 2 && cross_product(ans[k-2], ans[k-1], points.get(i)) <= 0)                 k--;             ans[k++] = points.get(i);         }          // Build upper hull         int t = k + 1;         for (int i = n-2; i >= 0; i--) {             while (k >= t && cross_product(ans[k-2], ans[k-1], points.get(i)) <= 0)                 k--;             ans[k++] = points.get(i);         }          List<Point> result = new ArrayList<>();         for (int i = 0; i < k-1; i++)             result.add(ans[i]);         return result;     }      static double dist(Point a, Point b) {         return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));     }      static double perimeter(List<Point> points) {         int n = points.size();         double perimeter = 0.0;         for (int i = 0; i < n-1; i++)             perimeter += dist(points.get(i), points.get(i+1));         perimeter += dist(points.get(0), points.get(n-1));         return perimeter;     }      public static void main(String[] args) throws java.lang.Exception {         List<Point> points = new ArrayList<>();         points.add(new Point(0, 3));         points.add(new Point(2, 2));         points.add(new Point(1, 1));         points.add(new Point(2, 1));         points.add(new Point(3, 0));         points.add(new Point(0, 0));         points.add(new Point(3, 3));          List<Point> convex_points = convex_hull(points);         System.out.println(perimeter(convex_points));     } } 
Python3
from typing import List from math import sqrt  class Point:     def __init__(self, x: int, y: int):         self.x = x         self.y = y  def cross_product(o: Point, a: Point, b: Point) -> int:     return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)  def convex_hull(points: List[Point]) -> List[Point]:     n = len(points)     if n <= 3:         return points      points.sort(key=lambda p: (p.x, p.y))     ans = [None] * (2 * n)      # Build lower hull     k = 0     for i in range(n):         while k >= 2 and cross_product(ans[k-2], ans[k-1], points[i]) <= 0:             k -= 1         ans[k] = points[i]         k += 1      # Build upper hull     t = k + 1     for i in range(n-2, -1, -1):         while k >= t and cross_product(ans[k-2], ans[k-1], points[i]) <= 0:             k -= 1         ans[k] = points[i]         k += 1      ans = ans[:k-1]     return ans  def dist(a: Point, b: Point) -> float:     return sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)  def perimeter(points: List[Point]) -> float:     n = len(points)     perimeter = 0.0     for i in range(n-1):         perimeter += dist(points[i], points[i+1])     perimeter += dist(points[0], points[n-1])     return perimeter  # Driver code points = [Point(0, 3), Point(2, 2), Point(1, 1), Point(2, 1), Point(3, 0), Point(0, 0), Point(3, 3)] convex_points = convex_hull(points) print(perimeter(convex_points)) 
JavaScript
class Point {   constructor(x, y) {     this.x = x;     this.y = y;   } }  function crossProduct(o, a, b) {   return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); }  function convexHull(points) {   let n = points.length;   if (n <= 3) {     return points;   }    points.sort((a, b) => a.x - b.x || a.y - b.y);   let ans = new Array(2 * n).fill(null);    // Build lower hull   let k = 0;   for (let i = 0; i < n; i++) {     while (k >= 2 && crossProduct(ans[k-2], ans[k-1], points[i]) <= 0) {       k--;     }     ans[k] = points[i];     k++;   }    // Build upper hull   let t = k + 1;   for (let i = n - 2; i >= 0; i--) {     while (k >= t && crossProduct(ans[k-2], ans[k-1], points[i]) <= 0) {       k--;     }     ans[k] = points[i];     k++;   }    ans = ans.slice(0, k-1);   return ans; }  function dist(a, b) {   return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); }  function perimeter(points) {   let n = points.length;   let perimeter = 0.0;   for (let i = 0; i < n - 1; i++) {     perimeter += dist(points[i], points[i+1]);   }   perimeter += dist(points[0], points[n-1]);   return perimeter; }  // Driver code let points = [new Point(0, 3), new Point(2, 2), new Point(1, 1), new Point(2, 1), new Point(3, 0), new Point(0, 0), new Point(3, 3)]; let convex_points = convexHull(points); console.log(perimeter(convex_points)); 
C#
using System; using System.Collections.Generic; using System.Linq;  class Point {     public int x, y;     public Point(int x, int y) {         this.x = x;         this.y = y;     } }  class MainClass {          // Cross product of two vectors OA and OB     // returns positive for counter clockwise     // turn and negative for clockwise turn     static int cross_product(Point o, Point a, Point b) {         return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);     }        // Returns a list of points on the convex hull     // in counter-clockwise order     static List<Point> convex_hull(List<Point> points) {         int n = points.Count;         if (n <= 3)             return points;          points.Sort((p1, p2) => {             if (p1.x == p2.x)                 return p1.y - p2.y;             return p1.x - p2.x;         });          Point[] ans = new Point[2 * n];         int k = 0;          // Build lower hull         for (int i = 0; i < n; i++) {                          // If the point at K-1 position is not a part             // of hull as vector from ans[k-2] to ans[k-1]             // and ans[k-2] to A[i] has a clockwise turn             while (k >= 2 && cross_product(ans[k-2], ans[k-1], points[i]) <= 0)                 k--;             ans[k++] = points[i];         }          // Build upper hull         int t = k + 1;         for (int i = n-2; i >= 0; i--) {                          // If the point at K-1 position is not a part             // of hull as vector from ans[k-2] to ans[k-1]             // and ans[k-2] to A[i] has a clockwise turn             while (k >= t && cross_product(ans[k-2], ans[k-1], points[i]) <= 0)                 k--;             ans[k++] = points[i];         }          List<Point> result = new List<Point>();         for (int i = 0; i < k-1; i++)             result.Add(ans[i]);         return result;     }        // Function to return the distance between two points     static double dist(Point a, Point b) {         return Math.Sqrt(Math.Pow(a.x - b.x, 2) + Math.Pow(a.y - b.y, 2));     }        // Function to return the perimeter of the convex hull     static double perimeter(List<Point> points) {         int n = points.Count;         double perimeter = 0.0;         for (int i = 0; i < n-1; i++)             perimeter += dist(points[i], points[i+1]);         perimeter += dist(points[0], points[n-1]);         return perimeter;     }        // Driver code     public static void Main(string[] args) {         List<Point> points = new List<Point>();                  // Add points         points.Add(new Point(0, 3));         points.Add(new Point(2, 2));         points.Add(new Point(1, 1));         points.Add(new Point(2, 1));         points.Add(new Point(3, 0));         points.Add(new Point(0, 0));         points.Add(new Point(3, 3));         // Find the convex hull         List<Point> convex_points = convex_hull(points);                  // Find the perimeter of convex polygon         Console.WriteLine(perimeter(convex_points));     } } 
Output:
12

Time Complexity : O(nlogn), where n is the number of points in the input vector.

Auxiliary Space Complexity : O(n), where n is the number of points in the input vector.


Next Article
Check if the given point lies inside given N points of a Convex Polygon

A

andrew1234
Improve
Article Tags :
  • Algorithms
  • Geometric
  • Competitive Programming
  • DSA
Practice Tags :
  • Algorithms
  • Geometric

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 leftmo
    13 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 ar
    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,
    11 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