![]() |
VOOZH | about |
Given the coordinates of two endpoints A(x1, y1), B(x2, y2) of the line segment and coordinates of a point E(x, y); the task is to find the minimum distance from the point to line segment formed with the given coordinates.
Note that both the ends of a line can go to infinity i.e. a line has no ending points. On the other hand, a line segment has start and endpoints due to which length of the line segment is fixed.
Examples:
Input: A = {0, 0}, B = {2, 0}, E = {4, 0}
Output: 2
To find the distance, dot product has to be found between vectors AB, BE and AB, AE.
AB = (x2 - x1, y2 - y1) = (2 - 0, 0 - 0) = (2, 0)
BE = (x - x2, y - y2) = (4 - 2, 0 - 0) = (2, 0)
AE = (x - x1, y - y1) = (4 - 0, 0 - 0) = (4, 0)
AB . BE = (ABx * BEx + ABy * BEy) = (2 * 2 + 0 * 0) = 4
AB . AE = (ABx * AEx + ABy * AEy) = (2 * 4 + 0 * 0) = 8
Therefore, nearest point from E to line segment is point B.
Minimum Distance = BE = = 2
Input: A = {0, 0}, B = {2, 0}, E = {1, 1}
Output: 1
Approach: The idea is to use the concept of vectors to solve the problem since the nearest point always lies on the line segment. Assuming that the direction of vector AB is A to B, there are three cases that arise:
1. The nearest point from the point E on the line segment AB is point B itself if the dot product of vector AB(A to B) and vector BE(B to E) is positive where E is the given point. Since AB . BE > 0, the given point lies in the same direction as the vector AB is and the nearest point must be B itself because the nearest point lies on the line segment.
2. The nearest point from the point E on the line segment AB is point A itself if the dot product of vector AB(A to B) and vector AE(A to E) is negative where E is the given point. Since AB . AE < 0, the given point lies in the opposite direction of the line segment AB and the nearest point must be A itself because the nearest point lies on the line segment.
3. Otherwise, if the two dot products AB.BE and AB.AE are of different signs, then the point E is perpendicular to the line segment AB and the perpendicular distance to the given point E from the line segment AB is the shortest distance. If some arbitrary point F is the point on the line segment which is perpendicular to E, then the perpendicular distance can be calculated as |EF| = |(AB X AE)/|AB||
Below is the implementation of the above approach:
1
Time Complexity: O(log(x2+y2)) because it is using inbuilt sqrt function
Auxiliary Space: O(1)