The Wayback Machine - https://web.archive.org/web/20240603030703/https://www.geeksforgeeks.org/minimum-distance-from-a-point-to-the-line-segment-using-vectors/
Open In App

Minimum distance from a point to the line segment using Vectors

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 = [Tex]\sqrt{\left ( y_{e}-y_{b} \right )^{2}+\left ( x_{e}-x_{b} \right )^{2}}[/Tex] = 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: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
 
// To store the point
#define Point pair<double, double>
#define F first
#define S second
using namespace std;
 
// Function to return the minimum distance
// between a line segment AB and a point E
double minDistance(Point A, Point B, Point E)
{
 
    // vector AB
    pair<double, double> AB;
    AB.F = B.F - A.F;
    AB.S = B.S - A.S;
 
    // vector BP
    pair<double, double> BE;
    BE.F = E.F - B.F;
    BE.S = E.S - B.S;
 
    // vector AP
    pair<double, double> AE;
    AE.F = E.F - A.F,
    AE.S = E.S - A.S;
 
    // Variables to store dot product
    double AB_BE, AB_AE;
 
    // Calculating the dot product
    AB_BE = (AB.F * BE.F + AB.S * BE.S);
    AB_AE = (AB.F * AE.F + AB.S * AE.S);
 
    // Minimum distance from
    // point E to the line segment
    double reqAns = 0;
 
    // Case 1
    if (AB_BE > 0) {
 
        // Finding the magnitude
        double y = E.S - B.S;
        double x = E.F - B.F;
        reqAns = sqrt(x * x + y * y);
    }
 
    // Case 2
    else if (AB_AE < 0) {
        double y = E.S - A.S;
        double x = E.F - A.F;
        reqAns = sqrt(x * x + y * y);
    }
 
    // Case 3
    else {
 
        // Finding the perpendicular distance
        double x1 = AB.F;
        double y1 = AB.S;
        double x2 = AE.F;
        double y2 = AE.S;
        double mod = sqrt(x1 * x1 + y1 * y1);
        reqAns = abs(x1 * y2 - y1 * x2) / mod;
    }
    return reqAns;
}
 
// Driver code
int main()
{
    Point A = make_pair(0, 0);
    Point B = make_pair(2, 0);
    Point E = make_pair(1, 1);
 
    cout << minDistance(A, B, E);
 
    return 0;
}

Java

// Java implementation of the approach
import java.io.*;
class GFG
{
 
static class pair
{
    double F, S;
    public pair(double F, double S)
    {
        this.F = F;
        this.S = S;
    }
    public pair() {
    }
}
 
// Function to return the minimum distance
// between a line segment AB and a point E
static double minDistance(pair A, pair B, pair E)
{
 
    // vector AB
    pair AB = new pair();
    AB.F = B.F - A.F;
    AB.S = B.S - A.S;
 
    // vector BP
    pair BE = new pair();
    BE.F = E.F - B.F;
    BE.S = E.S - B.S;
 
    // vector AP
    pair AE = new pair();
    AE.F = E.F - A.F;
    AE.S = E.S - A.S;
 
    // Variables to store dot product
    double AB_BE, AB_AE;
 
    // Calculating the dot product
    AB_BE = (AB.F * BE.F + AB.S * BE.S);
    AB_AE = (AB.F * AE.F + AB.S * AE.S);
 
    // Minimum distance from
    // point E to the line segment
    double reqAns = 0;
 
    // Case 1
    if (AB_BE > 0)
    {
 
        // Finding the magnitude
        double y = E.S - B.S;
        double x = E.F - B.F;
        reqAns = Math.sqrt(x * x + y * y);
    }
 
    // Case 2
    else if (AB_AE < 0)
    {
        double y = E.S - A.S;
        double x = E.F - A.F;
        reqAns = Math.sqrt(x * x + y * y);
    }
 
    // Case 3
    else
    {
 
        // Finding the perpendicular distance
        double x1 = AB.F;
        double y1 = AB.S;
        double x2 = AE.F;
        double y2 = AE.S;
        double mod = Math.sqrt(x1 * x1 + y1 * y1);
        reqAns = Math.abs(x1 * y2 - y1 * x2) / mod;
    }
    return reqAns;
}
 
// Driver code
public static void main(String[] args)
{
    pair A = new pair(0, 0);
    pair B = new pair(2, 0);
    pair E = new pair(1, 1);
 
    System.out.print((int)minDistance(A, B, E));
}
}
 
// This code is contributed by 29AjayKumar

C#

// C# implementation of the approach
using System;
 
class GFG
{
 
class pair
{
    public double F, S;
    public pair(double F, double S)
    {
        this.F = F;
        this.S = S;
    }
    public pair() {
    }
}
 
// Function to return the minimum distance
// between a line segment AB and a point E
static double minDistance(pair A, pair B, pair E)
{
 
    // vector AB
    pair AB = new pair();
    AB.F = B.F - A.F;
    AB.S = B.S - A.S;
 
    // vector BP
    pair BE = new pair();
    BE.F = E.F - B.F;
    BE.S = E.S - B.S;
 
    // vector AP
    pair AE = new pair();
    AE.F = E.F - A.F;
    AE.S = E.S - A.S;
 
    // Variables to store dot product
    double AB_BE, AB_AE;
 
    // Calculating the dot product
    AB_BE = (AB.F * BE.F + AB.S * BE.S);
    AB_AE = (AB.F * AE.F + AB.S * AE.S);
 
    // Minimum distance from
    // point E to the line segment
    double reqAns = 0;
 
    // Case 1
    if (AB_BE > 0)
    {
 
        // Finding the magnitude
        double y = E.S - B.S;
        double x = E.F - B.F;
        reqAns = Math.Sqrt(x * x + y * y);
    }
 
    // Case 2
    else if (AB_AE < 0)
    {
        double y = E.S - A.S;
        double x = E.F - A.F;
        reqAns = Math.Sqrt(x * x + y * y);
    }
 
    // Case 3
    else
    {
 
        // Finding the perpendicular distance
        double x1 = AB.F;
        double y1 = AB.S;
        double x2 = AE.F;
        double y2 = AE.S;
        double mod = Math.Sqrt(x1 * x1 + y1 * y1);
        reqAns = Math.Abs(x1 * y2 - y1 * x2) / mod;
    }
    return reqAns;
}
 
// Driver code
public static void Main(String[] args)
{
    pair A = new pair(0, 0);
    pair B = new pair(2, 0);
    pair E = new pair(1, 1);
 
    Console.Write((int)minDistance(A, B, E));
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// JavaScript implementation of the approach
 
// Function to return the minimum distance
// between a line segment AB and a point E
function minDistance( A,  B,  E)
{
 
    // vector AB
    var AB=[];
    AB.push (B[0] - A[0]);
    AB.push(B[1] - A[1]);
 
    // vector BP
    var BE=[];
    BE.push(E[0] - B[0]);
    BE.push(E[1] - B[1]);
 
    // vector AP
   var AE=[];
    AE.push(E[0] - A[0]),
    AE.push(E[1] - A[1]);
 
    // Variables to store dot product
    var AB_BE, AB_AE;
 
    // Calculating the dot product
    AB_BE=(AB[0] * BE[0] + AB[1] * BE[1]);
    AB_AE=(AB[0] * AE[0] + AB[1] * AE[1]);
 
    // Minimum distance from
    // point E to the line segment
    var reqAns = 0;
 
    // Case 1
    if (AB_BE > 0) {
 
        // Finding the magnitude
        var y = E[1] - B[1];
        var x = E[0] - B[0];
        reqAns = Math.sqrt(x * x + y * y);
    }
 
    // Case 2
    else if (AB_AE < 0) {
        var y = E[1] - A[1];
        var x = E[0] - A[0];
        reqAns = Math.sqrt(x * x + y * y);
    }
 
    // Case 3
    else {
 
        // Finding the perpendicular distance
       var x1 = AB[0];
        var y1 = AB[1];
       var x2 = AE[0];
        var y2 = AE[1];
        var mod = Math.sqrt(x1 * x1 + y1 * y1);
        reqAns = Math.abs(x1 * y2 - y1 * x2) / mod;
    }
    return reqAns;
}
 
var A =[0, 0];
    var B = [2, 0];
    var E = [1, 1];
 
    document.write( minDistance(A, B, E));
 
  
</script>

Python3

# Python3 implementation of the approach
from math import sqrt
 
# Function to return the minimum distance
# between a line segment AB and a point E
def minDistance(A, B, E) :
 
    # vector AB
    AB = [None, None];
    AB[0] = B[0] - A[0];
    AB[1] = B[1] - A[1];
 
    # vector BP
    BE = [None, None];
    BE[0] = E[0] - B[0];
    BE[1] = E[1] - B[1];
 
    # vector AP
    AE = [None, None];
    AE[0] = E[0] - A[0];
    AE[1] = E[1] - A[1];
 
    # Variables to store dot product
 
    # Calculating the dot product
    AB_BE = AB[0] * BE[0] + AB[1] * BE[1];
    AB_AE = AB[0] * AE[0] + AB[1] * AE[1];
 
    # Minimum distance from
    # point E to the line segment
    reqAns = 0;
 
    # Case 1
    if (AB_BE > 0) :
 
        # Finding the magnitude
        y = E[1] - B[1];
        x = E[0] - B[0];
        reqAns = sqrt(x * x + y * y);
 
    # Case 2
    elif (AB_AE < 0) :
        y = E[1] - A[1];
        x = E[0] - A[0];
        reqAns = sqrt(x * x + y * y);
 
    # Case 3
    else:
 
        # Finding the perpendicular distance
        x1 = AB[0];
        y1 = AB[1];
        x2 = AE[0];
        y2 = AE[1];
        mod = sqrt(x1 * x1 + y1 * y1);
        reqAns = abs(x1 * y2 - y1 * x2) / mod;
     
    return reqAns;
 
# Driver code
if __name__ == "__main__" :
 
    A = [0, 0];
    B = [2, 0];
    E = [1, 1];
 
    print(minDistance(A, B, E));
 
# This code is contributed by AnkitRai01


Output

1

Time Complexity: O(log(x2+y2)) because it is using inbuilt sqrt function
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Find middle point segment from given segment lengths
Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. The task is to find the segment which contains the middle point, If the middle segment do
6 min read
Find an Integer point on a line segment with given two ends
Given two points pointU and pointV in XY-space, we need to find a point which has integer coordinates and lies on a line going through points pointU and pointV. Examples: If pointU = (1, -1 and pointV = (-4, 1) then equation of line which goes through these two points is, 2X + 5Y = -3 One point with integer co-ordinate which satisfies above equatio
8 min read
Direction of a Point from a Line Segment
Direction of given point P from a line segment simply means given the co-ordinates of a point P and line segment (say AB), and we have to determine the direction of point P from the line segment. That is whether the Point lies to the Right of Line Segment or to the Left of Line Segment. The point might lie behind the line segment, in that case we a
8 min read
Shortest distance between a Line and a Point in a 3-D plane
Given a line passing through two points A and B and an arbitrary point C in a 3-D plane, the task is to find the shortest distance between the point C and the line passing through the points A and B.Examples: Input: A = (5, 2, 1), B = (3, 1, -1), C = (0, 2, 3) Output: Shortest Distance is 5 Input: A = (4, 2, 1), B = (3, 2, 1), C = (0, 2, 0) Output:
10 min read
Perpendicular distance between a point and a Line in 2 D
Given a point (x1, y1) and a line (ax + by + c = 0). The task is to find the perpendicular distance between the given point and the line. Examples : Input: x1 = 5, y1 = 6, a = -2, b = 3, c = 4 Output:3.32820117735Input: x1 = -1, y1 = 3, a = 4, b = -3, c = - 5 Output:3.6 Approach: The distance (i.e shortest distance) from a given point to a line is
9 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Equation of a straight line passing through a point and making a given angle with a given line
Given four integers a, b, c representing coefficients of a straight line with equation (ax + by + c = 0), the task is to find the equations of the two straight lines passing through a given point [Tex](x1, y1) [/Tex]and making an angle ? with the given straight line. Examples: Input: a = 2, b = 3, c = -7, x1 = 4, y1 = 9, ? = 30Output: y = -0.49x +1
16 min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Find the minimum sum of distance to A and B from any integer point in a ring of size N
Given a circular ring which has marking from 1 to N. Given two numbers A and B, you can stand at any place(say X) and count the total sum of the distance(say Z i.e., distance from X to A + distance from X to B). The task is to choose X in such a way that Z is minimized. Print the value of Z thus obtained. Note that X cannot neither be equal to A no
6 min read
Dynamic Segment Trees : Online Queries for Range Sum with Point Updates
Prerequisites: Segment TreeGiven a number N which represents the size of the array initialized to 0 and Q queries to process where there are two types of queries: 1 P V: Put the value V at position P.2 L R: Output the sum of values from L to R. The task is to answer these queries. Constraints: 1 ? N ? 1018Q ? 1051 ? L ? R? N Note: Queries are onlin
22 min read