Closest Pair Of Points In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Closest Pair Of Points In C++

Closest Pair Of Points In C++

BLUF: Mastering Closest Pair Of Points In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Closest Pair Of Points In C++

C++ is renowned for its efficiency. Learn how Closest Pair Of Points In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction

One of the primary challenges in computational geometry involves tackling the closest pair problem: determining the nearest pair of points among a set on a two-dimensional plane. This problem holds great practical importance, such as in air traffic control where it is crucial to detect and monitor aircraft that are in close proximity to each other to avoid potential collisions. Various methods exist to solve the closest pair problem, each with its own unique time complexities.

The previously discussed brute force approach, which involves calculating the distance between all pairs of points and choosing the shortest distance, operates with a time complexity of ο(n^2). Nonetheless, more efficient algorithms based on the Divide and Conquer technique have been devised, leading to an improved time complexity of О(n log n).

Here, we will discuss the resolution of the nearest pair of points issue in C++ utilizing two approaches: the brute-force technique and the Divide and Conquer Method. We will elucidate the reasoning behind these strategies and delineate each stage of the procedure, including code snippets.

Mathematical Background

The task of solving the Closest Pair of Points conundrum involves identifying the pair of points that are closest to each other within a specified set of points on a Euclidean plane. Mathematical principles play a pivotal role in this challenge, encompassing geometric understanding, distance calculations, and the intricacies of computational algorithms. This discussion delves into the characteristics of these elements to provide a concise overview.

Euclidean Distance

The formula to calculate the Euclidean distance between two points p= ( p x ,p y ) and q= ( q x ,q y ) on a 2D plane is expressed as follows:

It is known as the distance formula, which is obtained from the Pythagorean theorem. This formula states that the distance between two points is equal to the hypotenuse's length in a right triangle formed by the variance of the initial coordinates and the final coordinates.

Brute Force Approach

The brute-force method is applied to solve the Closest Pair of Points problem by computing the distance between each conceivable pair of points and identifying the shortest distance. The time complexity of this method is O(n^2), where n represents the quantity of points. This is due to the existence of n(n-1)/2 potential pairs of points.

Divide and Conquer Approach

To improve the efficiency of the brute force approach, we use the Divide and Conquer approach, which decreases the time complexity to Ο(n log⁡ n). This approach involves the following steps:

  • Sort the Points: First, sorting the points by their x-coordinates and this step has Ο(n log⁡ n). time complexity.
  • Divide: After that, divide the set of points into two halves. This is done by drawing a vertical line through the median point (in terms of x-coordinate).
  • Conquer: Recursively find the smallest distance in both the left and right halves.
  • Combine: The minimum distance between points in the left and right halves is compared. Additionally, points near the dividing line (within the smallest distance found so far) are checked to see if any pair spans across the line and has a smaller distance.
  • C++ Program to implement the Closest Pair of Points

Example

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits>

// Structure to represent a point in 2D plane
struct Point {
    int x, y;
};

// Function to compare points by their x-coordinates
bool compareX(const Point& a, const Point& b) {
    return a.x < b.x;
}

// Function to compare points by their y-coordinates
bool compareY(const Point& a, const Point& b) {
    return a.y < b.y;
}

// Function to calculate the distance between two points
double distance(const Point& p1, const Point& p2) {
    return sqrt((p1.x - p2.x) * (p1.x - p2.x) + 
                (p1.y - p2.y) * (p1.y - p2.y));
}

// A utility function to find the distance between the closescpp tutorials in strip of given size. All points in strip[] are sorted according to y coordinate.
double stripClosest(std::vector<Point>& strip, double d) {
    double min_dist = d; // Initialize the minimum distance as d

    std::sort(strip.begin(), strip.end(), compareY); // Sort the points according to Y coordinates

    // Pick all points one by one and try the nexcpp tutorials till the difference between y coordinates is smaller than d.
    for (size_t i = 0; i < strip.size(); ++i) {
        for (size_t j = i + 1; j < strip.size() && (strip[j].y - strip[i].y) < min_dist; ++j) {
            if (distance(strip[i], strip[j]) < min_dist) {
                min_dist = distance(strip[i], strip[j]);
            }
        }
    }

    return min_dist;
}

// A recursive function to find the smallest distance
double closestUtil(std::vector<Point>& points, size_t left, size_t right) {
    // If there are 2 or 3 points, then use brute force
    if (right - left <= 3) {
        double min_dist = std::numeric_limits<double>::max();
        for (size_t i = left; i < right; ++i) {
            for (size_t j = i + 1; j < right; ++j) {
                if (distance(points[i], points[j]) < min_dist) {
                    min_dist = distance(points[i], points[j]);
                }
            }
        }
        return min_dist;
    }

    // Find the middle point
    size_t mid = left + (right - left) / 2;
    Point midPoint = points[mid];

    // Consider the vertical line passing through the middle point
    // Calculate the smallest distance in the left and right halves
    double dl = closestUtil(points, left, mid);
    double dr = closestUtil(points, mid, right);

    // Find the smaller of the two distances
    double d = std::min(dl, dr);

    // Build an array strip[] that contains points close to the line passing through the middle point
    std::vector<Point> strip;
    for (size_t i = left; i < right; ++i) {
        if (std::abs(points[i].x - midPoint.x) < d) {
            strip.push_back(points[i]);
        }
    }

    // Find the closescpp tutorials in strip. Return the minimum of d and the closest distance in strip[]
    return std::min(d, stripClosest(strip, d));
}

// The main function that finds the smallest distance
double closest(std::vector<Point>& points) {
    std::sort(points.begin(), points.end(), compareX); // Sort the points according to X coordinates
    return closestUtil(points, 0, points.size());
}

int main() {
    std::vector<Point> points = {{2, 3}, {12, 30}, {40, 50}, {5, 1}, {12, 10}, {3, 4}};
    std::cout << "The smallest distance is " << closest(points) << std::endl;
    return 0;
}

Output:

Output

The smallest distance is 1.41421

Application of Closest Pair of Points

The Closest Pair of Points problem has numerous practical applications across various fields. Here are some key applications:

  • Air-Traffic Control Collision Detection: In air traffic control, it is crucial to control the distances that objects, for example, airplanes, take while flying so that they do not collide. Therefore, using the idea of the algorithm that calculates the closest pair of planes, one can determine the existing proximity and issue signals to separate the airplanes and prevent extremely dangerous situations.
  • Astronomy Identifying Star Clusters: In holding proximity relationships in stars or galaxies, astronomers apply the closest pair of points algorithms. Scientists discover the nearest neighbors by examining stellar distances, and thus, the patterns of star formations and other related phenomena are uncovered.
  • Geographical Information Systems (GIS) Nearest Neighbor Search: There are cases when the application has to find a set of closest objects, for example, finding the nearest hospital to the given coordinates or setting the nearescpp tutorials of interest. This implies in matters of route planning, resource provision, and the occurrence of any mishap.
  • Computer Graphics Collision Detection in Simulations: Collision detection is very vital in computer graphics and computer simulations with regard to how objects interact with each other. The algorithm of the closest pairs of points is useful in calculations that indicate when objects touch each other; this is particularly helpful in physical simulations, games, and virtual reality.
  • Robotics Path Planning: While the robots are moving in the environment, they should avoid the objects placed in front of them and have to seek the shortest possible path. Utilizing algorithms for the closest pair of points, robots can then easily identify nearby objects and paths that would not endanger them, further improving the robots' navigational ability in zones with high levels of complexity.
  • Clustering and Classification Data Analysis: Indeed, the closest pair of points algorithms is applied in the machine learning and data mining methodologies particularly in the clustering models including the hierarchical clustering. Thus, algorithms can join similar items together with the use of the shortest distance between the two points, which might help identify patterns, detect anomalies, and segment customers.
  • Networking Sensor Networks: Wireless sensor network particularly highlights the potential for measuring the distances between different nodes so that the coverage can be checked while communicating with the sensors. The closest pair of points algorithms is useful in the placement of sensors and the discovery of possible connectivity problems.
  • Medical Imaging Analysing Biological Structures: In medical imaging, the closest pair of points figuring out the degree of connection of different biological formations can be used. This is useful for purposes like identifying tumors where the thickness between cells or tissue could be an indication of the presence of the former.
  • Molecular Biology Protein Structure Analysis: Specifically, it can be critical in molecular biology where the structure of proteins is knowledge crucial essential to. Application of the closest pair of points algorithm proves to be useful when studying how atoms are positioned inside a protein and proteins folding and interactions.
  • Transportation and Logistics Optimizing Routes: In logistics and transportation one of the solutions sought is the identification of nearest depots or warehouses or delivery points to minimize movement distance. This increases efficiency and decreases costs in the supply chain management.
  • Conclusion

Hence, the challenge of determining the Closest Pair of Points stands as a fundamental concern within computational geometry, finding applications across diverse sectors such as air traffic management and molecular research. While the straightforward method is simple to deploy, its high computational demand poses a significant hurdle, especially when handling extensive datasets. In contrast, the strategy outlined in the publication leverages the Divide and Conquer technique, showcasing superior efficiency with a matching time complexity. This makes it well-suited for addressing practical scenarios requiring rapid and precise proximity identification. By leveraging the rich traditions of geometric principles and algorithmic enhancements within the realm of C++, resolving this issue becomes a manageable task. Mastering algorithms not only enhances computational efficiency but also exposes fundamental strategies for tackling a wide array of spatial challenges. Hence, the Closest Pair of Points conundrum holds paramount importance for examination and implementation across various domains.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience