CS138A Line Segment Intersection Peter Schröder
CS138A Intersection Problem statement given a set of n line segments in the plane, find all intersections examples brute force? can you do better Output sensitive algorithms running time is sensitive to the actual number of intersections
CS138A Plane Sweep Algorithm When can lines intersect? sweep line status of sweep line set of segments intersecting sweep line status only changes at discrete points status changes define event points end points as event points can still be quadratic maintain horizontally ordered list of event points
CS138A Line Sweep Algorithm Ordered sequence of events status changes at end points and at intersection points order changes at intersection points new strategy: only test neighbors against each other and only when events occur ignore boundary cases for now no segment horizontal any two segments intersect in at most one point no three segments intersect in one point
CS138A Line Sweep Algorithm Correctness Lemma 1: Let s i and s j be two non- horizontal segments whose interiors intersect in a single point p, and assume there is no third segment passing through p. Then there is an event point above p where s i and s j become adjacent and are tested for intersection
CS138A Line Sweep Algorithm Outline sweep line downward maintain ordered status update status at event points new segment inserted, old segment removed segment intersection only test neighbors in status against each other at event points order may change and action has to be taken
CS138A Line Sweep Algorithm Data structures event queue (balanced binary search tree) status structure (balanced binary tree) 1. FindIntersections(S) 2. Q = {}; 3. Insert all segment endpoints into Q 4. Record corresponding segment with upper endpoints 5. T = {}; 6. while( !Q.empty() ) 7. p = Q.extractMin(); 8. HandleEvenPoint(p);
CS138A HandleEventPoint 1. HandleEventPoint(p) 2. U(p) = segmentsUpper(p); S(p) = segmentsContaining(p); 3. L(p) = subset( S(p), T ).lower(p) 4. C(p) = subset( S(p), T ).interior(p) 5. if( |L(p)+U(p)+C(p)| > 1 ) 6. report p as intersection 7. T.delete( L(p)+C(p) ); T.insert( U(p)+C(p) ) 8. if( U(p)+C(p) == {} ) 9. s l = leftNeighbor( p, T ); s r = rightNeighbor( p, T ) 10. FindNewEvent( s l,s r,p ) 11. else 12. s’ = leftmostSegment( U(p)+C(p), T ) 13. s l = leftNeighbor( s’, T ) 14. FindNewEvent( s l,s’,p ) 15. s’’ = rightmostSegment( U(p)+C(p), T ) 16. s r = rightNeighbor( s’’, T ) 17. FindNewEvent( s’’,s r,p )
CS138A FindNewEvent 1. FindNewEvent( s l, s r, p ) 2. q = Intersect( s l, s r ) 3. if( q && (( q.y < p.y )|| 4. (( q.y == p.y ) && ( q.x > p.x ))) 5. !Q.contains(q) ) 6. Q.insert(q)
CS138A Correctness Does it find all intersections? Lemma 2: algorithm FindIntersections computes all intersection points and the segments that contain it correctly Running time Lemma 3: for n segments it is O(n log n + I log n), where I is the number of intersections