VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-simple-closed-path-for-a-given-set-of-points/

⇱ Find Simple Closed Path for a given set of points - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Simple Closed Path for a given set of points

Last Updated : 23 Jul, 2025

Given a set of points, connect the dots without crossing. 
 

πŸ‘ Simple Closed Path for a given set of points 1
πŸ‘ Simple Closed Path for a given set of points 2


Example: 

Input: points[] = {(0, 3), (1, 1), (2, 2), (4, 4),
 (0, 0), (1, 2), (3, 1}, {3, 3}};

Output: Connecting points in following order would
 not cause any crossing
 {(0, 0), (3, 1), (1, 1), (2, 2), (3, 3),
 (4, 4), (1, 2), (0, 3)}


We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use sorting. 

  • Find the bottom-most point by comparing y coordinate of all points. If there are two points with same y value, then the point with smaller x coordinate value is considered. Put the bottom-most point at first position. 
     

πŸ‘ find the bottom-most point by comparing y coordinate of all points

  • Consider the remaining n-1 points and sort them by polar angle in counterclockwise order around points[0]. If polar angle of two points is same, then put the nearest point first.
  • Traversing the sorted array (sorted in increasing order of angle) yields simple closed path. 
     

πŸ‘ traversing the sorted array


How to compute angles? 
One solution is to use trigonometric functions. 
Observation: We don’t care about the actual values of the angles. We just want to sort by angle. 
Idea: Use the orientation to compare angles without actually computing them!

Below is C++ implementation of above idea.  

Output: 

(0, 0), (3, 1), (1, 1), (2, 2), (3, 3),
(4, 4), (1, 2), (0, 3), 


Time complexity of above solution is O(n Log n) if we use a O(nLogn) sorting algorithm for sorting points.
Auxiliary Space: O(1), since no extra space has been taken.

Source: 
https://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
 

Comment
Article Tags:
Article Tags: