Minimum Cost to Connect All Points
Link points on a grid at the lowest total street distance by growing a tree one cheapest link at a time.
Given a list of points on a grid, each written as [x, y]|x1 - x2| + |y1 - y2|
Example 1
Output: 20
Example 2
Output: 18
The Idea
Imagine laying cable between buildings in a city whose streets form a grid. The cable has to follow the streets, so its length between two buildings is the blocks across plus the blocks up or down. That length is the Manhattan distance, named after the street grid of Manhattan.
Take Example 1 and number its points 0 to 4 in the order they are given. Point 0 is at (0,0) and point 1 at (2,2), so a link from 0 to 1 goes 2 across and 2 up, and costs 4. Any two of the five points can be linked, which makes 10 possible links.
Four of them are enough. Start with point 0 on its own: each new link can bring in one more point, so four links bring in the other four. A fifth link would close a loop, and removing any link of that loop keeps everything connected for no more cost.
A set of links that reaches every point and has no loop is called a spanning tree. "Spanning" means it reaches every point, and "tree" means it has no loops, so there is exactly one path between any two points. The problem asks for the cheapest one, the minimum spanning tree. So which four of the 10 links should we pick?
Grow the tree from one point. Start at point 0, and at each step look at every link from a point already in the tree to a point not yet in it. Take the cheapest of those links, and its outside point joins the tree. Look at the picture below.
The dashed path marked "2 across" and "2 up" is the street route behind the link from 0 to 1. The table on the right, "order the points join the tree", follows the growth. Point 0 starts at cost 0. From it, point 1 is 4 away, points 3 and 4 are 7 away, and point 2 is 13 away, so point 1 joins next with cost 4.
With points 0 and 1 in the tree, the cheapest link out is 1 to 3, cost 3. Then point 4 joins from 3 for 4, cheaper than the 7 it costs from point 0 or point 1. Point 2, far up at (3,10), comes last: its cheapest link is from point 1, cost 9. The row "total cost" adds them up: 0 + 4 + 3 + 4 + 9 = 20.
Why is taking the cheapest link out of the tree always safe? Any finished network must cross from the points inside to the points outside somewhere. If a network leaves out the cheapest crossing link, adding that link to it closes a loop. That loop crosses back over the divide on some other link, and removing that one keeps everything connected without raising the cost.
This way of growing a minimum spanning tree, one cheapest link at a time from a single starting point, is called Prim's algorithm.
Solution Approach
Turning Prim's algorithm into code means settling three things: how the links between points are stored, how to find the cheapest link out of the tree each round, and whether a heap or a plain array finds it faster. First, though, the slow way of trying every set of links shows why growing a tree is worth it.
Trying every set of links
Why not list every set of four links that forms a spanning tree and keep the cheapest? For the five points of Example 1 there are 125 such trees. The count grows far faster than the number of points: with 20 points there are 2018 trees, more than 1023. Growing the tree instead takes one round per point, and each round looks at every point twice.
Storing the links between points
How do the points become a graph? In graph terms, each of the five points is a vertex, and each of the 10 possible links is an edge whose weight is its Manhattan distance. The usual way to store a graph is an adjacency list: for each point, a list of its neighbours and the cost to each.
Here that list would be the same for every point: all the other points. For Example 1, point 0's list would read 1 (cost 4), 2 (cost 13), 3 (cost 7), 4 (cost 7). With n points there are n(n - 1)/2 links, 10 for the five points here, and the lists would hold each one twice. The distance is a quick sum of two differences, so the code computes it when it needs it and stores no list at all.
Keeping the cheapest link to each point
How do we find the cheapest link out of the tree without checking every pair of inside and outside points each round? For every point outside the tree, keep the cost of the cheapest link that reaches it from any point inside. The code keeps these costs in an array named best
When a new point joins, only its own links are new, so each outside point compares its bestbest
An array scan instead of a heap
Finding the smallest bestPriorityQueue
Here every point links to every other, so the heap would receive on the order of n2 entries and take O(n2 log n) time. The update after each new point joins already visits all n points, and picking the smallest one in a plain scan adds only another n steps, for O(n2) in all.
Another option is Kruskal's algorithm: sort all n(n - 1)/2 links by cost and take each one that does not close a loop. It works, but it has to build and sort every link, which takes O(n2) memory and O(n2 log n) time on this problem.
Java Solution
The method minCostConnectPoints
- First, create two arrays with one entry per point.
marks the points already in the tree.inTree holds the cheapest link from the tree to each point, and starts atbest , meaning "no link yet". SetInteger.MAX_VALUE , so point 0 joins first at no cost, and startbest[0] = 0 at 0.total - Run an outer loop n times, where n is the number of points, once for each point that joins the tree. Inside it, a first inner loop scans all points for
, the outside point with the smallestu . Startingbest at -1 lets the first outside point be taken without a comparison.u - Mark
inu and addinTree tobest[u] .total - A second inner loop goes over every point
still outside the tree, computes its Manhattan distancev tod , and keeps the smaller ofu andbest[v] .d - When the outer loop ends, every point has joined, so return
.total
The main
import java.util.Arrays;
public class MinimumCostToConnectPoints {
public static int minCostConnectPoints(int[][] points) {
int n = points.length;
boolean[] inTree = new boolean[n];
int[] best = new int[n]; // cheapest link from the tree to each point
Arrays.fill(best, Integer.MAX_VALUE);
best[0] = 0; // point 0 joins first, for free
int total = 0;
for (int added = 0; added < n; added++) {
int u = -1;
for (int i = 0; i < n; i++) { // the closest point not yet in the tree
if (!inTree[i] && (u == -1 || best[i] < best[u])) {
u = i;
}
}
inTree[u] = true;
total += best[u];
for (int v = 0; v < n; v++) { // u may offer a cheaper link to v
if (!inTree[v]) {
int d = Math.abs(points[u][0] - points[v][0])
+ Math.abs(points[u][1] - points[v][1]);
best[v] = Math.min(best[v], d);
}
}
}
return total;
}
public static void main(String[] args) {
System.out.println(minCostConnectPoints(
new int[][] {{0, 0}, {2, 2}, {3, 10}, {5, 2}, {7, 0}}));
System.out.println(minCostConnectPoints(new int[][] {{3, 12}, {-2, 5}, {-4, 1}}));
System.out.println(minCostConnectPoints(new int[][] {{0, 0}}));
System.out.println(minCostConnectPoints(new int[][] {{1, 1}, {1, 1}, {4, 5}}));
System.out.println(minCostConnectPoints(new int[][] {{0, 0}, {1, 0}, {2, 0}, {3, 0}}));
}
}
Running it prints:
20
18
0
7
3
The 20 and the 18 match the two examples. In Example 2, point 1 at (-2,5) is 12 from point 0 and 6 from point 2, and those two links make 18. The 0 on the third line comes from the single point: it joins at cost 0 and nothing else is left to link.
Look at the 7 on the fourth line. The two copies of (1,1) are 0 apart, so the second joins for free, and (4,5) is 3 across and 4 up from them. The last line, 3, is four points in a row, each one step from the next.
Why set best[0] = 0Integer.MAX_VALUEtotalint
Complexity
The work is n rounds, and in each round the code looks at every point twice.
- Time: O(n2), because each of the n rounds scans all n points once to pick the closest outside point and once more to update
.best - Space: O(n), because only
andinTree are kept, one entry per point, and the n(n - 1)/2 links between points are never stored.best
Both general algorithms have their own pages: