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 are less than 180degrees. A convex hull can be constructed for any set of points, regardless of their arrangement.
Convex Hull
Examples
Input: points[][] = [ [0, 0], [1, -4], [-1, -5], [-5, -3], [-3, -1], [-1, -3], [-2, -2], [-1, -1], [-2, -1], [-1, 1]] Output: [[-5, -3], [-1, 1], [0, 0], [1, -4], [-1, -5] Explantation: The figure below shows the points of a convex polygon. These points define the boundary of the polygon.
The Graham scan algorithm is a simple and efficient algorithm for computing the convex hull of a set of points. It works by iteratively adding points to the convex hull until all points have been added.
The algorithm starts by finding the point with the smallest y-coordinate. This point is always on the convex hull. The algorithm then sorts the remaining points by their polar angle with respect to the starting point.
The algorithm then iteratively adds points to the convex hull. At each step, the algorithm checks whether the last two points added to the convex hull form a right turn. If they do, then the last point is removed from the convex hull. Otherwise, the next point in the sorted list is added to the convex hull.
Step by Step Approach
Phase 1 (Sort points): The first step of the Graham Scan algorithm is to sort the points by their polar angle relative to the starting point. After sorting, the starting point is added to the convex hull, and the sorted points form a simple closed path.
Phase 2 (Accept or Reject Points): After forming the closed path, we traverse it to remove concave points. Using orientation, we keep the first two points and check the next point by considering the last three points be prev(p), curr(c) and next(n). If the angle formed by these three points is not counterclockwise, we discard (reject) the current point, otherwise, we keep (accept) it.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure to represent a pointstructPoint{doublex,y;// Operator to check equality of two pointsbooloperator==(constPoint&t)const{returnx==t.x&&y==t.y;}};// Function to find orientation of the triplet (a, b, c)// Returns -1 if clockwise, 1 if counter-clockwise, 0 if collinearintorientation(Pointa,Pointb,Pointc){doublev=a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y);if(v<0)return-1;if(v>0)return+1;return0;}// Function to calculate the squared distance between two pointsdoubledistSq(Pointa,Pointb){return(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}// Function to find the convex hull of a set of 2D pointsvector<vector<int>>findConvexHull(vector<vector<int>>points){// Store number of points pointsintn=points.size();// Convex hull is not possible if there are fewer than 3 pointsif(n<3)return{{-1}};// Convert points 2D vector into vector of Point structuresvector<Point>a;for(auto&p:points){a.push_back({(double)p[0],(double)p[1]});}// Find the point with the lowest y-coordinate (and leftmost in case of tie)Pointp0=*min_element(a.begin(),a.end(),[](Pointa,Pointb){returnmake_pair(a.y,a.x)<make_pair(b.y,b.x);});// Sort points based on polar angle with respect to the reference point p0sort(a.begin(),a.end(),[&p0](constPoint&a,constPoint&b){into=orientation(p0,a,b);// If points are collinear, keep the farthest one lastif(o==0){returndistSq(p0,a)<distSq(p0,b);}// Otherwise, sort by counter-clockwise orderreturno<0;});// Vector to store the points on the convex hullvector<Point>st;// Process each point to build the hullfor(inti=0;i<(int)a.size();++i){// While last two points and current point make a non-left turn, remove the middle onewhile(st.size()>1&&orientation(st[st.size()-2],st.back(),a[i])>=0)st.pop_back();// Add the current point to the hullst.push_back(a[i]);}// If fewer than 3 points in the final hull, return {-1}if(st.size()<3)return{{-1}};// Convert the final hull into a vector of vectors of integersvector<vector<int>>result;for(auto&p:st){result.push_back({(int)p.x,(int)p.y});}returnresult;}intmain(){// Define the points set of 2D pointsvector<vector<int>>points={{0,0},{1,-4},{-1,-5},{-5,-3},{-3,-1},{-1,-3},{-2,-2},{-1,-1},{-2,-1},{-1,1}};// Call the function to compute the convex hullvector<vector<int>>hull=findConvexHull(points);// If hull contains only {-1}, print the error resultif(hull.size()==1&&hull[0].size()==1){cout<<hull[0][0]<<" ";}else{// Print each point on the convex hullfor(auto&point:hull){cout<<point[0]<<", "<<point[1]<<"\n";}}return0;}
Java
importjava.util.*;classGfG{// Class to represent a point with x and y coordinatesstaticclassPoint{doublex,y;// Constructor to initialize pointPoint(doublex,doubley){this.x=x;this.y=y;}// Override equals to compare two points@Overridepublicbooleanequals(Objectobj){if(this==obj)returntrue;if(obj==null||getClass()!=obj.getClass())returnfalse;Pointt=(Point)obj;returnDouble.compare(t.x,x)==0&&Double.compare(t.y,y)==0;}}// Function to calculate orientation of ordered triplet (a, b, c)staticintorientation(Pointa,Pointb,Pointc){// Compute the cross product valuedoublev=a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y);// Return -1 for clockwise, 1 for counter-clockwise, 0 for collinearif(v<0)return-1;if(v>0)return1;return0;}// Function to compute square of distance between two pointsstaticdoubledistSq(Pointa,Pointb){return(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}// Function to find the convex hull of a set of pointsstaticint[][]findConvexHull(int[][]points){// Get number of points pointsintn=points.length;// Convex hull is not possible with less than 3 pointsif(n<3)returnnewint[][]{{-1}};// Convert int[][] points to list of Point objectsArrayList<Point>a=newArrayList<>();for(int[]p:points){a.add(newPoint(p[0],p[1]));}// Find the bottom-most point (and left-most if tie)Pointp0=Collections.min(a,(p1,p2)->{if(p1.y!=p2.y)returnDouble.compare(p1.y,p2.y);returnDouble.compare(p1.x,p2.x);});// Sort points based on polar angle with respect to p0a.sort((p1,p2)->{into=orientation(p0,p1,p2);// If collinear, sort by distance from p0if(o==0){returnDouble.compare(distSq(p0,p1),distSq(p0,p2));}// Otherwise sort by orientationreturn(o<0)?-1:1;});// Stack to store the points of convex hullStack<Point>st=newStack<>();// Traverse sorted pointsfor(Pointp:a){// Remove last point while the angle formed is not counter-clockwisewhile(st.size()>1&&orientation(st.get(st.size()-2),st.peek(),p)>=0)st.pop();// Add current point to the convex hullst.push(p);}// If convex hull has less than 3 points, it's invalidif(st.size()<3)returnnewint[][]{{-1}};// Convert the convex hull points into int[][]int[][]result=newint[st.size()][2];inti=0;for(Pointp:st){result[i][0]=(int)p.x;result[i][1]=(int)p.y;i++;}returnresult;}publicstaticvoidmain(String[]args){// points set of pointsint[][]points={{0,0},{1,-4},{-1,-5},{-5,-3},{-3,-1},{-1,-3},{-2,-2},{-1,-1},{-2,-1},{-1,1}};// Call function to get convex hullint[][]hull=findConvexHull(points);// Print resultif(hull.length==1&&hull[0].length==1){System.out.println(hull[0][0]);}else{for(int[]point:hull){System.out.println(point[0]+", "+point[1]);}}}}
Python
importmathfromfunctoolsimportcmp_to_key# Class to represent a pointclassPoint:def__init__(self,x,y):self.x=xself.y=y# Method to check equality of two pointsdef__eq__(self,other):returnself.x==other.xandself.y==other.y# Function to find orientation of the triplet (a, b, c)# Returns -1 if clockwise, 1 if counter-clockwise, 0 if collineardeforientation(a,b,c):val=(a.x*(b.y-c.y))+ \
(b.x*(c.y-a.y))+ \
(c.x*(a.y-b.y))ifval<0:return-1# Clockwiseelifval>0:return1# Counter-clockwisereturn0# Collinear# Function to calculate the squared distance between two pointsdefdistSq(a,b):return(a.x-b.x)**2+(a.y-b.y)**2# Function to find the convex hull from a list of 2D pointsdeffindConvexHull(points):n=len(points)# Convex hull is not possible if there are fewer than 3 pointsifn<3:return[[-1]]# Convert list of coordinates to Point objectsa=[Point(p[0],p[1])forpinpoints]# Find the point with the lowest y-coordinate (and leftmost in case of tie)p0=min(a,key=lambdap:(p.y,p.x))# Sort points based on polar angle with p0 as referencedefcompare(p1,p2):o=orientation(p0,p1,p2)ifo==0:returndistSq(p0,p1)-distSq(p0,p2)return-1ifo<0else1# Sort using custom comparatora_sorted=sorted(a,key=cmp_to_key(compare))# Remove collinear points (keep farthest)m=1foriinrange(1,len(a_sorted)):whilei<len(a_sorted)-1and \
orientation(p0,a_sorted[i],a_sorted[i+1])==0:i+=1a_sorted[m]=a_sorted[i]m+=1# Convex hull is not possible with fewer than 3 unique pointsifm<3:return[[-1]]# Initialize stack with first two pointsst=[a_sorted[0],a_sorted[1]]# Process the remaining pointsforiinrange(2,m):whilelen(st)>1and \
orientation(st[-2],st[-1],a_sorted[i])>=0:st.pop()st.append(a_sorted[i])# Final check for valid hulliflen(st)<3:return[[-1]]# Convert points back to list of [x, y]return[[int(p.x),int(p.y)]forpinst]# Test casepoints=[[0,0],[1,-4],[-1,-5],[-5,-3],[-3,-1],[-1,-3],[-2,-2],[-1,-1],[-2,-1],[-1,1]]# Compute the convex hullhull=findConvexHull(points)# Output the resultiflen(hull)==1andhull[0][0]==-1:print(-1)else:forpointinhull:print(f"{point[0]}, {point[1]}")
C#
usingSystem;usingSystem.Collections.Generic;classGfG{// Structure to represent a pointstructPoint{publicdoublex,y;publicPoint(doublex,doubley){this.x=x;this.y=y;}// Function to compare two pointspublicboolEquals(Pointother){returnthis.x==other.x&&this.y==other.y;}}// Function to find orientation of the triplet (a, b, c)// Returns -1 if clockwise, 1 if counter-clockwise, 0 if collinearstaticintorientation(Pointa,Pointb,Pointc){doublev=a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y);if(v<0)return-1;if(v>0)return1;return0;}// Function to calculate the squared distance between two pointsstaticdoubledistSq(Pointa,Pointb){return(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}// Function to find the convex hull of a set of 2D pointsstaticList<int[]>findConvexHull(int[,]input){intn=input.GetLength(0);// Convex hull is not possible if there are fewer than 3 pointsif(n<3)returnnewList<int[]>{newint[]{-1}};// Convert input array into list of Point structsList<Point>a=newList<Point>();for(inti=0;i<n;i++){a.Add(newPoint(input[i,0],input[i,1]));}// Find the point with the lowest y-coordinate (and leftmost in case of tie)Pointp0=a[0];foreach(varpina){if(p.y<p0.y||(p.y==p0.y&&p.x<p0.x)){p0=p;}}// Sort points based on polar angle with respect to the reference point p0a.Sort((a1,b1)=>{into=Orientation(p0,a1,b1);if(o==0){returnDistSq(p0,a1).CompareTo(DistSq(p0,b1));}returno<0?-1:1;});// List to store the points on the convex hullList<Point>st=newList<Point>();// Process each point to build the hullforeach(varptina){// While last two points and current point make a non-left turn, remove the middle onewhile(st.Count>1&&Orientation(st[st.Count-2],st[st.Count-1],pt)>=0){st.RemoveAt(st.Count-1);}// Add the current point to the hullst.Add(pt);}// If fewer than 3 points in the final hull, return [-1]if(st.Count<3)returnnewList<int[]>{newint[]{-1}};// Convert the final hull into List<int[]>List<int[]>result=newList<int[]>();foreach(varpinst){result.Add(newint[]{(int)p.x,(int)p.y});}returnresult;}staticvoidMain(){// Define the input set of 2D pointsint[,]points=newint[,]{{0,0},{1,-4},{-1,-5},{-5,-3},{-3,-1},{-1,-3},{-2,-2},{-1,-1},{-2,-1},{-1,1}};// Call the function to compute the convex hullList<int[]>hull=FindConvexHull(points);// If hull contains only [-1], print the error resultif(hull.Count==1&&hull[0].Length==1){Console.WriteLine(hull[0][0]);}else{// Print each point on the convex hullforeach(varpointinhull){Console.WriteLine(point[0]+", "+point[1]);}}}}
JavaScript
// Class to represent a pointclassPoint{constructor(x,y){this.x=x;this.y=y;}// Method to check equality of two pointsequals(t){returnthis.x===t.x&&this.y===t.y;}}// Function to compute orientation of the triplet (a, b, c)// Returns -1 for clockwise, 1 for counter-clockwise, 0 for collinearfunctionorientation(a,b,c){constv=a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y);if(v<0)return-1;// clockwiseif(v>0)return+1;// counter-clockwisereturn0;// collinear}// Function to compute squared distance between two pointsfunctiondistSq(a,b){return(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);}// Function to find the convex hull of a set of pointsfunctionfindConvexHull(points){constn=points.length;// Convex hull is not possible if there are fewer than 3 pointsif(n<3)return[[-1]];// Convert input array to Point objectsconsta=points.map(p=>newPoint(p[0],p[1]));// Find the point with the lowest y-coordinate (and leftmost if tie)constp0=a.reduce((min,p)=>(p.y<min.y||(p.y===min.y&&p.x<min.x))?p:min,a[0]);// Sort the points by polar angle with respect to p0a.sort((a,b)=>{consto=orientation(p0,a,b);// If collinear, place the farther point laterif(o===0){returndistSq(p0,a)-distSq(p0,b);}// Otherwise, order based on counter-clockwise directionreturno<0?-1:1;});// Remove duplicate collinear points (keep farthest one)letm=1;for(leti=1;i<a.length;i++){// Skip closer collinear pointswhile(i<a.length-1&&orientation(p0,a[i],a[i+1])===0){i++;}// Keep current point in placea[m]=a[i];m++;}// If fewer than 3 points remain, hull is not possibleif(m<3)return[[-1]];// Initialize the convex hull stack with first two pointsconstst=[a[0],a[1]];// Process the remaining pointsfor(leti=2;i<m;i++){// While the last three points do not make a left turn, pop the middle onewhile(st.length>1&&orientation(st[st.length-2],st[st.length-1],a[i])>=0){st.pop();}// Add current point to stackst.push(a[i]);}// Final validation: if fewer than 3 points in stack, hull is not validif(st.length<3)return[[-1]];// Convert hull points to [x, y] arraysreturnst.map(p=>[Math.round(p.x),Math.round(p.y)]);}// Test caseconstpoints=[[0,0],[1,-4],[-1,-5],[-5,-3],[-3,-1],[-1,-3],[-2,-2],[-1,-1],[-2,-1],[-1,1]];// Compute the convex hullconsthull=findConvexHull(points);// Output the resultif(hull.length===1&&hull[0][0]===-1){console.log(-1);}else{hull.forEach(point=>{console.log(`${point[0]}, ${point[1]}`);});}
Output
-1 -5
1 -4
0 0
-3 -1
-5 -3
Time Complexity: O(n log n), for finding the bottom-most point takes O(n), sorting the points takes O(n log n), and building the hull through stack operations takes O(n). Space Complexity: O(n), due to the stack used for storing the points during the hull construction, with no significant additional space required.
Applications of Convex Hulls:
Convex hulls have a wide range of applications, including:
Collision detection: Convex hulls can be used to quickly determine whether two objects are colliding. This is useful in computer graphics and physics simulations.
Image processing: Convex hulls can be used to segment objects in images. This is useful for tasks such as object recognition and tracking.
Computational geometry: Convex hulls are used in a variety of computational geometry algorithms, such as finding the closest pair of points and computing the diameter of a set of points.
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
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.