The problem
A directed graph is given as adjacency lists: adj[u] lists the vertices that u has an edge to, in order. Run a depth-first search exactly as the recursive version in lesson 3 would: start at vertex 0, try the neighbours of each vertex in the order of its list, and when the search from 0 is over, start again from the smallest vertex not yet visited.
A vertex finishes when every neighbour in its list has been tried. Return the vertices in the order they finish.
finish_order([[1, 2], [3], [3], []]) # [3, 1, 2, 0]
finish_order([[2, 1], [3], [3], []]) # [3, 2, 1, 0]
finish_order([[1], [], [0], []]) # [1, 0, 2, 3]
In the first example, 0 goes to 1 and 1 goes to 3. Vertex 3 has no neighbours, so it finishes first, then 1. Back at 0, the next neighbour is 2; its only neighbour, 3, is already visited, so 2 finishes, and then 0.
Limits
- Up to 100,000 vertices and 300,000 edges. Lists may contain a vertex itself, or the same neighbour twice.
- Paths can be 100,000 vertices deep. A recursive function fails: Python stops at about 1,000 nested calls, and the browser may stop sooner. Keep your own stack. The big tests have 3 seconds each.
Builds on GRPH-3 Depth-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 | Neighbour order matters | Not run | |
| 3 | Several starts | Not run | |
| 4 | A cycle | Not run | |
| 5 | A loop and a repeated edge | Not run | |
| 6 | No edges | Not run | |
| 7 | Finishing is not visiting | Not run | |
| 8 | 1,000 vertices | Not run | |
| 9 | A path of 100,000 | Not run | |
| 10 | 100,000 vertices, 300,000 edges | Not run | |
| 11 | A long cycle with branches | Not run |