The problem
The network is as in P1: stations 0 to n − 1, and lines (u, v) that run both ways. Return a route from station s to station t that uses the fewest lines, as a list of stations that starts with s and ends with t. Return None if no route exists.
edges = [(0, 5), (5, 6), (0, 1), (1, 2), (2, 3), (3, 4), (4, 6)]
route(7, edges, 0, 6) # [0, 5, 6]
route(3, [(0, 1)], 0, 2) # None
route(3, [(0, 1)], 1, 1) # [1]
When several routes are equally short, any of them is accepted. The tests check that your list is a route (each pair of stations next to each other in it is joined by a line) and count its lines.
Limits
- Up to 500,002 stations and 500,001 lines.
- Routes can be 100,000 lines long, so a recursive search is too deep. One station can have 500,000 neighbours waiting in the queue at once. The big tests have 3 seconds each, and 4 for that one.
Builds on GRPH-2 Breadth-first search.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Start is the end | Not run | |
| 3 | No route | Not run | |
| 4 | A direct line listed last | Not run | |
| 5 | Lines both ways and twice | Not run | |
| 6 | A ladder | Not run | |
| 7 | Endless rings | Not run | |
| 8 | A path of 100,000 | Not run | |
| 9 | 500,000 stops one step away | Not run | |
| 10 | 100,000 random lines | Not run | |
| 11 | Two separate halves | Not run |