Pick the Quietest Depot

Medium · Topological Sort & Shortest Paths · about 25 min

A courier company has n depots, numbered 0 to n - 1. Each [a, b, km] in roads is a two-way road of length km. Two depots are close if the shortest drive between them is at most limit km.

The company wants a quiet spot for a new warehouse: return the depot that is close to the fewest other depots. If several depots tie, return the one with the largest number.

  • 1 <= n <= 100, 1 <= km <= 10^4. Some depots may not be connected at all.

Example: quietest_depot(4, [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]], 4) → 3 (depots 0 and 3 are each close to 2 others, and 3 is larger).

Hints

  • You need shortest distances between all pairs of a small graph. Which algorithm gives the whole table at once?
  • Floyd-Warshall: for each stepping stone k (the outer loop), see if going through k is shorter for every pair.
  • Count close depots per row of the table. Be careful with 'at most' and with the tie rule.

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

More Topological Sort & Shortest Paths problems