Wire Up the Sensors

Medium · Topological Sort & Shortest Paths · about 25 min

A farm has sensors at points points[i] = [x, y]. A cable between two sensors follows the field rows, so its length is the Manhattan distance |x1 - x2| + |y1 - y2|.

Return the smallest total cable length that connects all sensors (every sensor can reach every other through cables, and cables only join sensors).

  • 1 <= len(points) <= 1000, -10^6 <= x, y <= 10^6. Two sensors may sit at the same point.

Example: sensor_wiring_cost([[0, 0], [0, 4], [4, 0], [4, 4]]) → 12 (three cables of length 4).

Hints

  • Connecting everything as cheaply as possible is a minimum spanning tree.
  • Every pair is a possible cable. Instead of listing all of them, grow one wired group from any sensor.
  • Keep the cheapest cable from each unwired sensor to the group. Add the closest one, then let it offer cheaper cables to the rest.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems