GRPH-P2

A shortest route

Practice 2 of 7Graphs11 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Start is the endNot run
3No routeNot run
4A direct line listed lastNot run
5Lines both ways and twiceNot run
6A ladderNot run
7Endless ringsNot run
8A path of 100,000Not run
9500,000 stops one step awayNot run
10100,000 random linesNot run
11Two separate halvesNot run