Skip to main content

Sweep Line Algorithm

The Sweep Line Algorithm is a powerful approach used in computational geometry to solve problems involving geometric figures (e.g., finding intersections, computing areas, etc.). The idea is to "sweep" a vertical line across the plane from left to right and process events as they occur.

Key Concepts:​

  1. Event Points: These are the key positions in the plane where important changes happen. These might include the start or end of a line, or an intersection between two objects.
  2. Active Set: As the sweep line moves, it maintains an active set of objects (e.g., lines, segments) that intersect the current position of the sweep line.

Code Implementation​

The following code snippets demonstrate the implementation of the Sweep Line Algorithm in Python, C++, and Java. The algorithm is used to find intersections among a set of line segments by sweeping a line across the plane.

import heapq

class Event:
def __init__(self, x, start, segment):
self.x = x
self.start = start
self.segment = segment

def __lt__(self, other):
return self.x < other.x or (self.x == other.x and self.start > other.start)

def sweep_line(segments):
"""Sweep line algorithm to find intersections in a set of line segments.

Args:
segments: A list of tuples representing line segments (x1, y1, x2, y2).

Returns:
A list of intersection points.
"""
events = []
for seg in segments:
x1, y1, x2, y2 = seg
events.append(Event(x1, True, seg))
events.append(Event(x2, False, seg))

heapq.heapify(events)
active_segments = []
intersections = []

while events:
event = heapq.heappop(events)

if event.start:
active_segments.append(event.segment)
else:
active_segments.remove(event.segment)

# Check for intersections among active segments
for i in range(len(active_segments)):
for j in range(i + 1, len(active_segments)):
inter = find_intersection(active_segments[i], active_segments[j])
if inter:
intersections.append(inter)

return intersections

def find_intersection(seg1, seg2):
"""Helper function to check if two line segments intersect.

Args:
seg1: First line segment.
seg2: Second line segment.

Returns:
The intersection point if it exists, otherwise None.
"""
# Implement the logic to check for intersection and calculate the intersection point
pass

# Example Usage
segments = [(1, 1, 5, 5), (1, 5, 5, 1)]
intersections = sweep_line(segments)
print(f"Intersections: {intersections}")

Applications in Competitive Programming:​

  1. Finding Segment Intersections: Used to detect where line segments cross, which is important in geometry-based problems.
  2. Computing the Union of Rectangles: Calculate the area covered by a union of several rectangles.
  3. Closest Pair of Points: Efficiently find the closest pair of points in a 2D plane.