The user wants a program to compute the convex hull using Graham's scan.
I need to decide which programming language to use. Python is a safe bet for readability and ease of understanding, especially for geometric algorithms. C++ is also good for performance, but Python is often preferred for educational or quick implementation requests unless specified otherwise. I will stick with Python.
Algorithm Steps (Graham's Scan):
- Find the Pivot: Identify the point with the lowest y-coordinate (and lowest x-coordinate in case of ties). This point is guaranteed to be on the convex hull. Let's call it P0.
- Sort Points: Sort the remaining N−1 points based on the polar angle they make with P0. If two points have the same angle, keep the one closer to P0.
- Initialize Stack: Push the first three points (the pivot and the first two sorted points) onto a stack.
- Iterate and "Left Turn" Check:
- For each remaining point p:
- Pop points from the stack while the angle formed by the point before the top of the stack, the top of the stack, and the current point p makes a "non-left turn" (i.e., a right turn or collinear).
- Push p onto the stack.
- Result: The stack contains the vertices of the convex hull in counter-clockwise order.
Key Geometric Concept: Cross Product (Determinant)
To determine the turn direction (Left, Right, Collinear) for three points A,B,C:
Vector AB=(Bx−
Vector
Cross Product .
- Result >0: Counter-clockwise (Left Turn).
- Result <0: Clockwise (Right Turn).
- Result =0: Collinear.
Code Structure:
- A
Point class (or just use tuples/lists). A class is cleaner.
- A function to calculate polar angle (relative to the pivot).
- A function to calculate the distance (for tie-breaking collinear points).
- The main
graham_scan function.
- Example usage with a set of points.
Refining the Sorting Step:
- We need a custom sort key.
- The key should return the angle.
- Tie-breaking: if angles are equal, distance. We want to keep the farthest point for the hull boundary? Actually, in Graham scan, if points are collinear with the pivot, we usually keep the one farthest away for the hull edge, but we must be careful with intermediate collinear points.
- Correction: Standard implementation usually filters collinear points on the hull edges. However, for the sort step specifically: if angle(A) == angle(B), keep the one closer to pivot? Actually, it's better to keep the farther one for the hull, but strictly speaking, the algorithm works by removing collinear intermediate points.
- Let's stick to the standard robust method:
- Sort by polar angle.
- If polar angles are equal, sort by distance (closest to farthest).
- During the scan, if a "left turn" is strictly required (counterclockwise), collinear points will be popped. If we want to include collinear points on the hull edge, we treat "collinear" as "left". Standard convex hull usually just wants vertices. I will implement the "strict left turn" version (pops if collinear or right turn) to get the minimal vertices.
Edge Cases:
- Fewer than 3 points.
- All points collinear.
Drafting the Code (Mental or Scratchpad):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def polar_angle(p0, p1):
return math.atan2(p1.y - p0.y, p1.x - p0.x)
def distance(p0, p1):
return (p1.x - p0.x)**2 + (p1.y - p0.y)**2
def cross_product(o, a, b):
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
# Main logic
points = [...]
# Find bottom-most
points.sort(key=lambda p: (p.y, p.x))
pivot = points[0]
# Sort rest
rest = points[1:]
rest.sort(key=lambda p: (polar_angle(pivot, p), distance(pivot, p)))
# Stack
stack = [pivot, rest[0], rest[1]] # needs check for len < 3
for p in rest[2:]:
while len(stack) > 1 and cross_product(stack[-2], stack[-1], p) <= 0: # <= 0 pops collinear/right
stack.pop()
stack.append(p)
Refinement on Tie-breaking:
If we sort by distance (closest to farthest) and the cross product check is <= 0 (non-left turn), the algorithm will pop closer collinear points and keep the farthest one. This is the correct behavior for a minimal convex hull.
Visuals:
I should probably mention how to visualize it or run it. A simple text output of points is fine.
Let's write the Python code.
Here is a complete implementation of the Convex Hull algorithm using Graham's Scan in Python.
The Algorithm
- Find the Pivot: Select the point with the lowest y-coordinate (and lowest x in case of a tie). This point is guaranteed to be on the 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.
- Scan: Iterate through the sorted points. If the sequence of the last two points and the current point constitutes a "right turn" (non-counterclockwise), remove the middle point from the hull. Repeat this until a left turn is found.
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})"
# Define equality for testing purposes
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def convex_hull_graham(points):
"""
Computes the convex hull of a set of 2D points using Graham's scan.
:param points: List of Point objects
:return: List of Point objects representing the convex hull vertices
"""
# Step 1: Find the pivot (point with lowest y, then lowest x)
# This point is guaranteed to be on the hull.
points = sorted(points, key=lambda p: (p.y, p.x))
pivot = points[0]
# Step 2: Sort points by polar angle with respect to the pivot
# If angles are equal, sort by distance to pivot (closer first)
def polar_angle(p):
# Return angle in radians
return math.atan2(p.y - pivot.y, p.x - pivot.x)
def distance(p):
# Squared distance to avoid sqrt computation cost
return (p.x - pivot.x)**2 + (p.y - pivot.y)**2
# Sort the rest of the points
points = points[1:]
points.sort(key=lambda p: (polar_angle(p), distance(p)))
# Step 3: Process sorted points to build the hull
# We use a stack to maintain the hull vertices
hull = [pivot]
for p in points:
# While the turn formed by the last two points in hull
# and the current point p is not a "left turn" (counter-clockwise),
# pop the last point from the hull.
while len(hull) >= 2 and cross_product(hull[-2], hull[-1], p) <= 0:
hull.pop()
hull.append(p)
return hull
def cross_product(o, a, b):
"""
Computes the 2D cross product of OA and OB vectors.
Returns a positive value if OAB makes a counter-clockwise turn (Left).
Returns a negative value if OAB makes a clockwise turn (Right).
Returns 0 if the points are collinear.
"""
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
# --- Example Usage ---
if __name__ == "__main__":
# Define a set of points
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)
# Compute Hull
hull_result = convex_hull_graham(input_points)
print("\nConvex Hull Vertices (Counter-Clockwise):")
for p in hull_result:
print(p)
Explanation of Key Functions
-
cross_product(o, a, b):
This determines the orientation of three points. In a 2D plane, if we stand at point o, looking at a:
- If
b is to our left, the value is positive (Counter-Clockwise).
- If
b is to our right, the value is negative (Clockwise).
- If
b is straight ahead, the value is zero (Collinear).
Graham's scan requires Counter-Clockwise turns to maintain the convex shape. If we encounter a Clockwise turn, it means we "caved in" towards the center, so we discard that point.
-
Sorting Strategy:
We sort primarily by the angle relative to the bottom-most point (pivot). The math.atan2 function is used because it correctly handles angles in all four quadrants. We also use a tie-breaker (distance) so that if multiple points lie on the same ray from the pivot, the closest one is processed first (though the loop logic handles collinear points effectively, this ensures stability).
-
The Loop:
The logic while ... <= 0 removes collinear points and right turns. This ensures the output is strictly convex. If you want to include collinear points on the edges of the hull, you can change <= 0 to < 0.