DSA Factory
Free Graphs lessonsGraphs · Stage 7 · Spanning trees · Step 2

Growing one network from a point

When every pair of points could be joined, grow a single network outwards, always adding the nearest point not yet in it. About 16 minutes.

Grow one network

You have points on a map and can run a cable between any two, costing the Manhattan distance, which means the horizontal gap plus the vertical gap. Connect them all as cheaply as possible.

Start with one point as the network. For every other point, remember how close it is to the network. Repeat: pick the outsider that is closest, add it, and pay that distance. Adding it may bring some outsiders closer, so check each against the new member.

Pick: the outsider closest to the network.
Update: every outsider's closest distance.
In code
def dist(a, b):
    dx = abs(a[0] - b[0])
dy = abs(a[1] - b[1])
return dx + dy
Four points: A(0,0) B(1,3) C(6,1) D(7,7). Nearest distance to the network after each step.
BCD
near
4
7
14
total
0

The network is just A. Distances to A: B is 4, C is 7, D is 14.

Move 1 of 6

The loop

Do n minus 1 rounds. In each round, scan the outsiders for the one with the smallest near value. Add its distance to the total and mark it inside. Then for every other outsider, lower its near value if the new member is closer than anything in the network so far.

No sorting, and no heap needed, because scanning n points each round is already as cheap as keeping a heap would be when there are about n squared links anyway. The answer is the total after the last round.

Only outsiders: are candidates; skip points already inside.
n minus 1 rounds: one for each point added.
In code
near[j] = min(near[j], dist(pick, j))
Quick check

A new point joins the network. What do you update?

  1. AEvery outsider's closest distance, if the new point is closer than what it had
  2. BNothing, since distances never change
  3. COnly the total, by adding all remaining distances
Show the answer

Every outsider's closest distance, if the new point is closer than what it had. The new member may be the nearest link for some outsiders.

Your problem

Connect the points

points[i] = [x, y] is the position of a point on a map. You may run a cable between any two points, and a cable costs the Manhattan distance between them, which is |x1 − x2| + |y1 − y2|. Return the smallest total cable cost so that every point is connected to every other, directly or through other points.

Example
points = [[0, 0], [2, 2], [3, 10], [5, 2]] → 16

1 ≤ points ≤ 500 · −10,000 ≤ x, y ≤ 10,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve