SPAN-P3

Connect the points

Practice 3 of 4Minimum spanning trees8 tests

The problem

Stations stand at the given points of a city laid out in square blocks. A line between two stations costs their Manhattan distance, abs(x1 - x2) + abs(y1 - y2): the blocks you walk along streets. Any two stations may be joined. Return the least total cost of lines that join every station to every other.

connect_points([(0, 0), (2, 2), (3, 10), (5, 2), (7, 0)])
# 20
connect_points([(5, -5)])
# 0

Coordinates are whole numbers. Two stations may stand at the same point.

Limits

  • Up to 2,000 points, so up to 1,999,000 possible lines.
  • Making and sorting every possible line is too slow. The big tests have 3 seconds each.

Builds on SPAN-3 Prim.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2One pointNot run
3Two pointsNot run
4The same place twiceNot run
5In a rowNot run
6300 pointsNot run
72,000 pointsNot run
82,000 points, many tiesNot run