Shortest distance between points algorithm

前端 未结 7 2075
独厮守ぢ
独厮守ぢ 2020-11-29 03:47

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 calcu

7条回答
  •  星月不相逢
    2020-11-29 04:02

    One possibility would be to sort the points by their X coordinates (or the Y -- doesn't really matter which, just be consistent). You can then use that to eliminate comparisons to many of the other points. When you're looking at the distance between point[i] and point[j], if the X distance alone is greater than your current shortest distance, then point[j+1]...point[N] can be eliminated as well (assuming i -- if j, then it's point[0]...point[i] that are eliminated).

    If your points start out as polar coordinates, you can use a variation of the same thing -- sort by distance from the origin, and if the difference in distance from the origin is greater than your current shortest distance, you can eliminate that point, and all the others that are farther from (or closer to) the origin than the one you're currently considering.

提交回复
热议问题