Program to find minimum cost to connect each Cartesian coordinates in C++

Suppose we have a list of 2D Cartesian coordinate points (x, y). We can connect (x0, y0) and (x1, y1), whose cost is |x0 - x1| + |y0 - y1|. If we are allowed to connect any number of points, we have to find the minimum cost necessary such that every point is connected by a path.

So, if the input is like points = [[0, 0],[0, 2],[0, -2],[2, 0],[-2, 0], [2, 3], [2, -3]],

then the output will be 14 because, from (0, 0) to (0, 2),(0, -2),(2, 0),(-2, 0), costs are 2, total is 8, and (2, 3) is nearest from (0, 2), cost is |2+1| = 3 and for (2, -3) it is nearest to (0, -2), cost is also 3. so total cost is 8 + 6 = 14.

To solve this, we will follow these steps −

  • MAX := inf
  • Define a function interval(), this will take i, j, and points array p,
  • return |(p[i, x] - p[j, x]) + |p[i, y] - p[j, y]||
  • From the main method, do the following −
  • n := size of p
  • if n
  • Define an array called distance with n slots and fill with MAX
  • Define an array visited of size n
  • distance[0] := 0
  • for initialize i := 0, when i
  • min_d := MAX
  • node := 0
  • for initialize j := 0, when j
  • if visited[j] is false and distance[j]
  • min_d := distance[j]
  • node := j
  • visited[node] := true
  • cost := cost + distance[node]
  • for initialize j := 0, when j
  • if visited[j] is false, then −
    • d := interval(node, j, p)
    • distance[j] := minimum of distance[j] and d
  • return cost
  • Example

    Let us see the following implementation to get better understanding −

    #include 
    #include 
    #define MAX 99999
    using namespace std;
    
    int interval(int i, int j, vector>& p) {
       return abs(p[i][0] - p[j][0]) + abs(p[i][1] - p[j][1]);
    }
    
    int solve(vector>& p) {
       int n = p.size(), cost = 0;
       if (n  distance(n, MAX);
       vector visited(n);
    
       distance[0] = 0;
    
       for (int i = 0; i > points = {{0, 0},{0, 2},{0, -2},{2, 0},{-2, 0}, {2, 3}, {2, -3}};
    cout 

    Input

    {{0, 0},{0, 2},{0, -2},{2, 0},{-2, 0}, {2, 3}, {2, -3}}

    Output

    14
    Updated on: 2021-10-16T11:53:51+05:30

    306 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements