The fewest transfers
- O(n) · Medium
- Full plan
- Python
- JavaScript
- dictionaries
- sets
- loops
Problem
Owen has just moved and still has not got the hang of the city's transit. He does not care how long it takes or how far he walks: what he wants is to make the fewest legs, because every transfer throws him off. A leg is getting on at one stop and off at another one that is connected straight to it.
Write a function that takes network, start and finish. network is a dictionary where each key is the name of a stop and its value is the list of the stops you reach straight from there. The connections work both ways and are written down on both sides: if "Lake" is in the list of "Center", "Center" is in the list of "Lake". No stop is repeated inside the same list, none is connected to itself, and every stop that shows up in a list is also a key of network. There are 1 to 20 stops and 0 to 40 connections. start and finish are names of stops of network.
Return a whole number: the fewest legs to go from start to finish. If the two are the same stop, Owen is already where he wanted to be: return 0. If there is no way to get there, return -1.
With {"South": ["Center"], "Center": ["South", "Lake"], "Lake": ["Center"]}, going from "South" to "Lake" is 2 legs: South to Center and Center to Lake. From "South" to "South" it is 0. And in {"North": ["West"], "West": ["North"], "Lighthouse": []} there is no way to go from "North" to "Lighthouse": it returns -1.
Examples
The example
{"South": ["Center"], "Center": ["South", "Lake"], "Lake": ["Center"]}, "South", "Lake" → 2
The same stop
{"South": ["Center"], "Center": ["South", "Lake"], "Lake": ["Center"]}, "South", "South" → 0
A single leg
{"South": ["Center"], "Center": ["South", "Lake"], "Lake": ["Center"]}, "South", "Center" → 1
There is no way to get there
{"North": ["West"], "West": ["North"], "Lighthouse": []}, "North", "Lighthouse" → -1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def legs(network, start, finish):
passJavaScript
function legs(network, start, finish) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.