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], link them all together as cheaply as possible. A link between two points costs their Manhattan distance, |x1 - x2| + |y1 - y2|. Every point must be reachable from every other, with exactly one path between any two. Return the smallest total cost.

Example 1
Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
Output: 20
Example 2
Input: points = [[3,12],[-2,5],[-4,1]]
Output: 18
Solution

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 five points of Example 1 on a grid, joined by four links: 0 to 1 costs 4, 1 to 3 costs 3, 3 to 4 costs 4 and 1 to 2 costs 9. The table beside it lists the order the points join the tree: 0, 1, 3, 4, 2, for a total cost of 20.

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 best value with its distance to the new point and keeps the smaller one. The next point to join is the outside point with the smallest best. In Example 1, after point 1 joins, point 3's value drops from 7 to 3, and that 3 is the smallest, so point 3 joins next.

An array scan instead of a heap

Finding the smallest best value by scanning all n points sounds wasteful. Many versions of Prim's algorithm keep the links waiting to be picked in a heap, which would hand back the cheapest waiting link quickly. Java's PriorityQueue can serve as that heap. A heap pays off when each point has only a few links.

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 works in these steps:

  1. First, create two arrays with one entry per point. inTree marks the points already in the tree. best holds the cheapest link from the tree to each point, and starts at Integer.MAX_VALUE, meaning "no link yet". Set best[0] = 0, so point 0 joins first at no cost, and start total at 0.
  2. 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 u, the outside point with the smallest best. Starting u at -1 lets the first outside point be taken without a comparison.
  3. Mark u in inTree and add best[u] to total.
  4. A second inner loop goes over every point v still outside the tree, computes its Manhattan distance d to u, and keeps the smaller of best[v] and d.
  5. When the outer loop ends, every point has joined, so return total.

The main method runs both examples, a single point, two points at the same spot plus a third, and four points in a row.

Java
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:

Output
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] = 0 when point 0 is picked first anyway? Without that line, point 0 still joins first, but its Integer.MAX_VALUE goes into total. The other four costs then push the sum past what an int can hold, and it wraps round to a negative number: Example 1 returns -2147483629 instead of 20.

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 inTree and best are kept, one entry per point, and the n(n - 1)/2 links between points are never stored.

Both general algorithms have their own pages: Prim's Algorithm and Kruskal's Algorithm.