1. Understand the Goal: The user wants a program that computes the convex hull of a set of points using Graham's scan algorithm.
-
Identify the Algorithm: Graham's scan is a method of finding the convex hull of a finite set of points in the plane with time complexity O(nlogn).
-
Determine the Steps of Graham's Scan:
- Step 1: Find the Pivot. Select the point with the lowest y-coordinate. If there's a tie, pick the one with the lowest x-coordinate. This point (let's call it P0) is guaranteed to be a vertex of the convex hull.
- Step 2: Sort Points. Sort the remaining points P1,…,Pn−1 based on the polar angle they make with P0. If two points have the same angle, keep the one furthest away and discard the closer one (collinearity handling).
- Step 3: Scan. Initialize a stack. Push the first three points (P0,P1,P2) onto the stack. Iterate through the sorted points. For each point, check if the sequence of the top two points on the stack and the current point makes a "non-left turn" (a right turn or collinear). If it does, pop the stack. Repeat until a left turn is made. Push the current point.
- Step 4: Result. The stack now contains the vertices of the convex hull in counter-clockwise order.
-
Select a Programming Language: Python is a good choice for readability and ease of understanding mathematical vector operations, but C++ or Java are better for performance in competitive programming contexts. Since the user didn't specify, I'll provide a Python solution because it's concise and widely understood, perhaps with a brief mention or implementation of the cross-product logic.
-
Drafting the Code (Python):
-
Writing the Code (Mental Draft):
import math
points = [(0,0), (1,1), (2,2), ...] # Example
# 1. Find P0
start = min(points, key=lambda p: (p[1], p[0]))
# 2. Sort
def polar_angle(p):
return math.atan2(p[1] - start[1], p[0] - start[0])
# Remove start point from list to sort
points.remove(start)
points.sort(key=polar_angle) # This is a bit weak on ties.
# Better: key=lambda p: (polar_angle(p), distance_sq(start, p)))
# Re-insert start at beginning? No, usually kept separate or added at end to close loop.
# 3. Stack
hull = [start, points[0], points[1]]
for p in points[2:]:
while len(hull) > 1 and cross(hull[-2], hull[-1], p) <= 0:
hull.pop()
hull.append(p)
-
Edge Cases:
- Less than 3 points: Cannot form a convex hull polygon. Just return all points.
- Collinear points: The choice of
<= 0 vs < 0 in the while loop determines if we keep collinear points on the edges. Usually, we want the minimum set of vertices (strict convex hull), so <= 0 is preferred.
-
Refining the Sort: Using atan2 is O(1) but math.atan2 involves floating point. For a purely integer geometric problem, using a comparator based on cross product is more robust, but Python's sort requires a key or a functor for cmp_to_key. To keep the code clean and understandable, atan2 is acceptable for a general-purpose demonstration.
-
Final Code Structure:
- Class
Point (optional, but nice) or just functions.
- Function
convex_hull(points).
- Driver code to demonstrate.
-
Reviewing the request: "Create a program". I should provide a complete, runnable script.
-
Self-Correction during coding:
- Wait, what if multiple points have the exact same coordinates? Deduplication is often required. I'll add a note or basic handling.
- What about the "last" point in the sort? If the points are collinear along the longest reach from the start point, the standard sort puts the closest one first. The algorithm processes them. If the turn is straight (0), and we use
<= 0, it pops. So it keeps the furthest one. That works.
-
Constructing the Explanation:
- Explain the algorithm steps (Sort, Scan).
- Explain the Cross Product (determines left/right turn).
- Provide the Python code.
- Provide sample input/output.
-
Code Polish:
- Use
math.atan2 for the angle.
- Calculate cross product: (b.x−a.x)∗(c.y−a.y).
(Self-Correction on logic): If I have a set of points all on a line.
P0,P1,P2.
line up to . Cross product is 0.
If condition is , pop . Result is . Correct (segment hull).
If condition is , keep . Result . Correct (if we want all boundary points).
I will use to return the minimal vertex set (strict convex hull).
Let's write the solution.
Here is a complete, runnable Python program that implements the Graham's Scan algorithm to compute the Convex Hull of a set of 2D points.
The Algorithm Logic
- Find the Pivot: Identify the point with the lowest Y-coordinate (and lowest X if there are ties). This point is guaranteed to be part of the convex hull.
- Sort Points: Sort the remaining points based on the polar angle they make with the pivot. If two points have the same angle, keep the one closer to the pivot (and discard the further one, as it cannot be a vertex of the hull if enclosed by a closer point).
- Scan: Iterate through the sorted points. If turning from the previous point to the current point involves a "right turn" (or a straight line), the previous point cannot be part of the convex hull and is removed from the stack. This continues until we return to the pivot.
Python Implementation
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"({self.x}, {self.y})"
# Enable subtraction of points to get vectors
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def compute_convex_hull(points):
"""
Computes the convex hull of a list of points using Graham's Scan.
Returns a list of points representing the convex hull vertices
in counter-clockwise order.
"""
# 1. Handle edge cases
if len(points) <= 1:
return points
# 2. Find the pivot (point with lowest y, then lowest x)
# This point is guaranteed to be on the hull.
pivot = min(points, key=lambda p: (p.y, p.x))
# 3. Sort the points based on polar angle with respect to the pivot
# We perform the sort in-place or create a new list.
# If angles are equal, sort by distance (closer first).
def sort_key(p):
# Return tuple: (angle, distance_squared)
# If p is the pivot itself, angle is undefined, put it first.
if p == pivot:
return (0, 0)
dx = p.x - pivot.x
dy = p.y - pivot.y
angle = math.atan2(dy, dx)
dist_sq = dx*dx + dy*dy
return (angle, dist_sq)
sorted_points = sorted(points, key=sort_key)
# Helper function for Cross Product
# Cross product of vector AB and vector BC
# If > 0: Counter-clockwise turn (Left)
# If < 0: Clockwise turn (Right)
# If == 0: Collinear
def cross_product(o, a, b):
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
# 4. Build the Hull using a Stack
stack = []
for p in sorted_points:
# While the stack has at least 2 points and the turn is not counter-clockwise
# (i.e., we are turning right or going straight), pop the stack.
while len(stack) >= 2 and cross_product(stack[-2], stack[-1], p) <= 0:
stack.pop()
stack.append(p)
return stack
# --- Driver Code / Example Usage ---
if __name__ == "__main__":
# Create a set of random or specific points
# Some points are inside, some form the outer boundary
input_points = [
Point(0, 3),
Point(1, 1),
Point(2, 2),
Point(4, 4),
Point(0, 0),
Point(1, 2),
Point(3, 1),
Point(3, 3)
]
print("Input Points:", input_points)
hull = compute_convex_hull(input_points)
print("Convex Hull Vertices:", hull)
How it works
- Cross Product (
cross_product): This is the geometric engine of the algorithm. Given three points O,A,B, the cross product determines the "turn" direction.
- If we are turning Right (clockwise), the result is negative.
- If we are turning Left (counter-clockwise), the result is positive.
- Since we want the outer boundary, we must always turn Left.
- Sorting: We pick the bottom-most point as the anchor (
pivot). We then sort every other point by angle relative to this pivot.
- The Loop: We iterate through the sorted points. If adding a new point causes us to make a "Right Turn" (or stay straight) relative to the previous segment, the middle point of that turn creates a "dent" or concavity. Because a convex hull must be strictly convex (no dents), we discard that middle point (
stack.pop()). We check this repeatedly until we are making a valid Left Turn again.