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}")

Time Complexity

  • Best Case: O(N log N) (when there are no intersections)
  • Average Case: O((N + K) log N)
  • Worst Case: O((N + K) log N) where N is the number of line segments and K is the number of intersection points. Note: The provided naive implementations check all active segments in O(A^2) where A is the number of active segments, making them O(N^2) in the worst case. An optimal implementation uses a balanced Binary Search Tree to maintain active segments, achieving O((N + K) log N).

Space Complexity

  • O(N) where N is the number of line segments. The event queue holds up to 2N events, and the active set holds at most N segments at any given time.

Explanation

The Sweep Line algorithm optimizes processing by sorting spatial events (like the start and end of segments) from left to right, which takes O(N log N) time. It then maintains an active set of elements that currently intersect the sweep line. By finding intersections only among adjacent segments in the active set (usually maintained with a balanced BST), it avoids checking every possible pair, dramatically reducing runtime compared to a brute-force approach.

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.