Skip to the code
cf.
+25 XP

#470 Wire All Kiosks Cheaply

medium

A mall is installing self-service kiosks at the points in kiosks, where kiosks[i] = [x, y]. Cables run along the floor grid, so a cable between two kiosks costs the Manhattan distance |x1 - x2| + |y1 - y2|. Any two kiosks can be wired directly.

Write wiringCost(kiosks) that returns the smallest total cable cost that connects every kiosk, directly or through other kiosks.

Example 1

Input: kiosks = [[0,0],[3,1],[6,0],[3,6]]
Output: 13

Wire kiosk 1 to kiosk 0 (4), to kiosk 2 (4), and to kiosk 3 (5): 4 + 4 + 5 = 13.

Example 2

Input: kiosks = [[5,5]]
Output: 0

A single kiosk needs no cable.

Constraints

  • 1 <= kiosks.length <= 1000
  • -10^6 <= x, y <= 10^6
  • All points are different.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).