Problem Description
Given an array of points representing coordinates on a 2D-plane, our goal is to connect all the points such that the cost of connecting any two points is defined by their Manhattan distance. We want to create a configuration (a tree) where there is exactly one simple path between any two points, and the total cost is minimized. This is essentially a Minimum Spanning Tree (MST) problem on a complete graph where the vertices are the points and the edge costs are the Manhattan distances between points.
Key Insights
- The problem can be reinterpreted as finding a Minimum Spanning Tree (MST) on a complete graph.
- Manhattan distance is used to calculate the weight/cost between every pair of vertices.
- Prim’s or Kruskal’s algorithm can be applied to solve the MST problem.
- A direct construction of the complete graph is unnecessary; distances can be computed on the fly, which is efficient given the problem constraints.
Space and Time Complexity
Time Complexity: O(n^2)
Space Complexity: O(n)
Solution
We can solve the problem using Prim’s algorithm. We start from an arbitrary point (for example, the first point) and iteratively add the point that has the smallest distance to the growing MST. Instead of explicitly constructing all the edges, we compute the Manhattan distance on the fly between the current MST and the remaining points. An array is used to track the minimum connection cost for each point that is not yet included in the tree. At each iteration, we select the point with the smallest cost to add into the MST and update the costs for the remaining points. This approach guarantees that we connect all points with the minimum total cost.