Wiring the Campsites

MediumgreedyAlso known as Min Cost to Connect All Points

A campground is adding electric hook-ups. Each pitch has grid coordinates [x, y] on the site map. Cable has to run along the gravel paths, which go only north-south and east-west, so a cable between two pitches costs |x1 - x2| + |y1 - y2| metres.

Power can pass through a pitch to reach the next one, so every pitch just needs to be connected to the rest by some chain of cables. The manager wants the least total cable that does it.

Your task

Write minCable(pitches). Each entry is [x, y]. You may lay a cable between any two pitches, at a cost equal to their distance along the paths, |x1 - x2| + |y1 - y2|. Return the smallest total cost so that every pitch is connected to every other, directly or through other pitches.

One pitch needs no cable: return 0. Two pitches can share the same coordinates; joining them costs 0.

minCable(pitches: int[][]) → int

Examples

Example 1
Input
pitches = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]
Output
20
Why

Lay [0,0]–[2,2] (4), [2,2]–[5,2] (3), [5,2]–[7,0] (4) and [2,2]–[3,10] (9). Total 20. The cable to [3,10] is the expensive one, and 9 is the cheapest cable that reaches it: every other one costs at least 10.

Example 2
Input
pitches = [[0, 0], [1, 0], [10, 0], [11, 0]]
Output
11
Why

Two pairs, each with a 1-metre cable. Linking each pitch to its own nearest neighbor gives just those two cables, which leaves two separate groups. One more cable is needed to bridge the gap, and the cheapest is [1,0]–[10,0] at 9. Total 1 + 1 + 9 = 11.

Constraints

  • 1 ≤ pitches.length ≤ 1,000
  • -1,000,000 ≤ x, y ≤ 1,000,000
Start with brute force

List all n(n - 1)/2 possible cables and try every subset of n - 1 of them that connects everything, keeping the cheapest.

With just 20 pitches there are 190 cables and about 6 × 1025 ways to pick 19 of them. Greedy choices are provably safe here, so you never need to search. Kruskal's algorithm (sort all cables, add each one that joins two different groups) also works, but with 1,000 pitches it has to sort about 500,000 cables first.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code