Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest distance between points algorithm

Given a set of points on a plane, find the shortest line segment formed by any two of these points.

How can I do that? The trivial way is obviously to calculate each distance, but I need another algorithm to compare.

like image 414
geord Avatar asked Oct 21 '09 16:10

geord


People also ask

How do you find the shortest distance between points?

The shortest distance between two points is a straight line. This distance can be calculated by using the distance formula. The distance between two points ( x 1 , y 1 ) and ( x 2 , y 2 ) can be defined as d = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 .

What is the shortest distance between points P and Q?

Hence, the shortest distance between P and Q is √29.


2 Answers

http://en.wikipedia.org/wiki/Closest_pair_of_points

The problem can be solved in O(n log n) time using the recursive divide and conquer approach, e.g., as follows:

  • Sort points along the x-coordinate
  • Split the set of points into two equal-sized subsets by a vertical line x = xmid
  • Solve the problem recursively in the left and right subsets. This will give the left-side and right-side minimal distances dLmin and dRmin respectively.
  • Find the minimal distance dLRmin among the pair of points in which one point lies on the left of the dividing vertical and the second point lies to the right.
  • The final answer is the minimum among dLmin, dRmin, and dLRmin.
like image 90
Wayne Sheppard Avatar answered Sep 20 '22 15:09

Wayne Sheppard


I can't immediately think of a quicker alternative than the brute force technique (although there must be plenty) but whatever algorithm you choose don't calculate the distance between each point. If you need to compare distances just compare the squares of the distances to avoid the expensive and entirely redundant square root.

like image 26
Troubadour Avatar answered Sep 18 '22 15:09

Troubadour