CodeArchon

mediumAdvanced GraphsLinkedInGoogle

Grid-Point Spanner

A fiber contractor connects every village (point) at minimum trenching cost using Manhattan distance between any pair.

Given n points, connect all with minimum total cost where cost between two points is their Manhattan distance.

Choose approach

(0,0)
u
(2,2)
(3,10)
(5,2)
(7,0)
1/5
Narrationstep 1 of 5

Add point 0 with min-edge cost 0. Running total = 0.

1def minCostConnectPoints(points):
2 n = len(points)
3 inMST = [False]*n
4 dist = [float('inf')]*n; dist[0] = 0
5 total = 0
6 for _ in range(n):
7 u = -1
8 for i in range(n):
9 if not inMST[i] and (u == -1 or dist[i] < dist[u]): u = i
10 inMST[u] = True; total += dist[u]
11 for v in range(n):
12 if not inMST[v]:
13 d = abs(points[u][0]-points[v][0]) + abs(points[u][1]-points[v][1])
14 if d < dist[v]: dist[v] = d
15 return total
Variables
added=0
cost=0
total=0

How to think about it

  1. Complete graph on n points -> n² edges; Prim's dense is cheapest.
  2. `dist[v]` = minimum edge from any inMST node to v so far.
  3. Each iteration admits one node and relaxes its neighbors.

Edge cases to catch in interview

  • Single point -> 0.
  • Collinear points -> MST is the straight chain.

Examples

Example 13
{"points":[[0,0],[1,1],[1,0],[0,1]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed