Min Cost to Connect All Points
Connect every sprinkler with the least total pipe
DSA, Medium, Advanced Graphs
Which structure or algorithm, and what does it cost.
A field has n sprinklers at positions [x, y]. A pipe between two sprinklers costs |x1 - x2| + |y1 - y2|. Lay pipes so water can travel from any sprinkler to any other, directly or through others. Return the smallest total cost. Two sprinklers may share a position. One sprinkler alone needs no pipe.
Examples
Constraints
- 1 <=
n<= 2,000. - -100,000 <=
x,y<= 100,000.
Your answer must contain
- Why the cheapest connection has no loop; the method; code; time and memory cost; a hand trace of example 1; the edge cases.
Target Aim for O(n^2) time and O(n) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Every pair of sprinklers could have a pipe, but you only need enough to connect them all. How many pipes does the cheapest answer use?
Hint 2 the approach
The cheapest answer never has a loop. Why? Now grow one connected group: which pipe is always safe to add next?
Hint 3 the key step
For each sprinkler outside the group, store its cheapest distance to the group. Add the one with the smallest value, update the others, and repeat.
Walkthrough
Full walkthrough brute force to best
Brute force
Try every set of n - 1 pipes out of the n(n-1)/2 possible ones. Keep the sets that connect all sprinklers and take the cheapest. The number of sets grows far too fast for 2,000 sprinklers.
Best method
The cheapest answer uses exactly n - 1 pipes and has no loop: in a loop you can remove the costliest pipe and stay connected. Grow one group of connected sprinklers from sprinkler 0. For each sprinkler outside the group, keep the cost of its cheapest pipe to the group. Add the outside sprinkler with the smallest cost, add that cost to the total, then lower the other costs using the pipes to the new sprinkler. The smallest outside pipe is always safe: any full connection must cross from the group to the outside, and no crossing pipe is cheaper. This method is called Prim's algorithm, and the pipe set it builds is a minimum spanning tree. Distances are computed when needed, so no list of all pairs is stored.
Hand trace
Example 1: start with sprinkler 0 at cost 0. Its pipe costs to sprinklers 1 to 4 are 7, 7, 14 and 1. Take sprinkler 4 at cost 1: the costs for sprinklers 1, 2 and 3 become 6, 6 and 13. Take sprinkler 1 at cost 6: sprinkler 3 drops to 7. Take sprinkler 2 at cost 6, then sprinkler 3 at cost 7. The total is 1 + 6 + 6 + 7 = 20.
Code
def min_pipe_cost(sprinklers):
n = len(sprinklers)
cheapest = [float("inf")] * n # cheapest pipe from each sprinkler to the connected group
cheapest[0] = 0
inside = [False] * n
total = 0
for _ in range(n):
i = min((j for j in range(n) if not inside[j]), key=lambda j: cheapest[j])
inside[i] = True
total += cheapest[i]
for j in range(n):
if not inside[j]:
d = abs(sprinklers[i][0] - sprinklers[j][0]) + abs(sprinklers[i][1] - sprinklers[j][1])
if d < cheapest[j]:
cheapest[j] = d
return totalTime and memory
O(n^2) time: n rounds, and each round scans n sprinklers twice. O(n) memory for the cost list and the group marks.
Common mistakes
- Joining each sprinkler only to its nearest neighbour. That can leave separate groups that never connect.
- Adding a pipe between two sprinklers that are already in the group. That makes a loop and wastes cost.
- Pushing a pipe to every outside sprinkler into a heap. That is O(n^2 log n) time and O(n^2) memory. With all pairs allowed, the plain scan is faster.
- Keeping an old cost after the group grows. Take the smaller of the old cost and the cost to the new sprinkler.