Closest Pair
Closest Pair
q
p
Time Complexity: O( N ) 2 3
Plane-Sweep Algorithm
• Maybe we can avoid checking the distance between every pair...
• Plane-sweep worked for segment intersection...
• Key observation: if the closest pair of points to the left of the sweep
line is distance d apart, the next point encountered can’t be a closest
pair with any point more than d units to the left of the line
d
p
The closest point to the left of p can only be in the red-shaded region
4
Stored Information
• Maintain the following information:
– closest pair (a,b) found so far, and distance d between them.
– ordered dictionary S of the points lying in a strip of width d
to the left of the sweep line, using the y-coordinates as keys
b
d
a p
d
dictionary S
5
Updating
• When the sweep line encounters a point p:
– update dictionary so it only contains points that might be a closest pair with p
– remove all points r such that x(p)-x(r)>d from S
– find the closest point q to p in S
– if d(p,q) < d then update the current closest pair and distance
– insert p into S
d
q
6
Searching the Dictionary d
7
Searching the Dictionary II
d
• But how to search in a half-circle? p
– a rectangle is almost a half-circle…
2d
– do a range search in the interval [y(p)-d,y(p)+d]
– this will get all the points in the half-circle (and
maybe some others)
• Use brute-force to check the distance to each
point returned by the range query
• But isn’t that still a potentially large number of
points?
– actually, there are at most 6 2d p
– key observation: all of the points in the dictionary are
at least distance d from each other
8
d
Putting It All Together
sort points by x-coordinate and store in ordered sequence X
maintain references to two positions in sequence
-firstInStrip: the leftmost point in S
-lastInStrip: the new point to be added to S
at each step..
lastInStrip X.after(lastInStrip) // advance lastInStrip
// remove points that are no longer candidates from dictionary
while x(point(firstInStrip)) < x(point(lastInStrip))-d do
S.remove(point(firstInStrip))
firstInStrip X.after(firstInStrip)
// update closest point information
find point q closest to point(lastInStrip) in S
if d(p,q) < d then update closest pair
d d(p,q)
9
S.insert(point(lastInStrip)) // insert new point into dictionary
An Example
nothing within
rectangle; closest
pair not updated
d