Shortest Path Visiting All Nodes
Real-world version: Calling at Every HubThe statement here is our own: the same inputs, outputs and technique.
A network has hubs numbered 0 through n - 1, and links[i] lists the hubs joined directly to hub i. Every link works both ways, no hub is joined to itself, and every hub can be reached from every other one.
A courier may set off from whichever hub it likes, travels one link at a time, and may pass through any hub as often as it pleases.
Return the fewest links the courier has to cross to have called at every hub.
Examples
Example 1
- Input
- links = [[1], [0, 2], [1, 3], [2]]
- Output
- 3
The hubs form a single chain, so setting off at one end and walking to the other calls at all four hubs across three links.
Example 2
- Input
- links = [[1, 2, 3, 4], [0], [0], [0], [0]]
- Output
- 6
Four hubs hang off one middle hub. Setting off from a hanging hub, the courier has to come back through the middle between each pair of them, which is six links.
Example 3
- Input
- links = [[]]
- Output
- 0
A single hub is already called at, so nothing has to be crossed.
Constraints
- 1 <= links.length <= 12
- 0 <= links[i].length < links.length
- no hub is listed among its own links
- if hub b is listed for hub a then hub a is listed for hub b
- every hub can be reached from every other one
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def shortest_path_length(links: list[list[int]]) -> int:public int shortestPathLength(int[][] links)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Cheapest Flights Within K StopsReal-world version: Limited Handoff Courier RouteMedium
- Beautiful ArrangementReal-world version: Divisible Crate PlacementsMedium
- Partition to K Equal Sum SubsetsReal-world version: Dealing Counterweights Onto HoistsMedium
- Shopping OffersReal-world version: Cheapest Basket at the Fastener CounterMedium