Ctrl K

Every Route to the Exit

Medium
An escape room has n rooms numbered 0 to n - 1. From room i, one-way doors lead to the rooms listed in links[i]. The doors are arranged so you can never get back to a room you have already passed: there are no cycles. The player starts in room 0 and the exit is room n - 1. Return every distinct route from the start to the exit; each route is the list of rooms in the order visited, from 0 to n - 1. The routes may be listed in any order.
Example 1
links=[[1, 2], [2, 3], [3], []] → [[0, 1, 3], [0, 2, 3], [0, 1, 2, 3]]

There are three routes from room 0 to exit 3: 0 → 1 → 2 → 3, 0 → 1 → 3 and 0 → 2 → 3.

Example 2
links=[[2], [], [1]] → [[0, 2]]

The only route is 0 → 2 → 1, since the exit is room n - 1 = 1.

Example 3
links=[[], [2], []] → []

Room 0 leads nowhere, so there are no routes.

Constraints
  • 2 ≤ n ≤ 15
  • 0 ≤ links[i][j] < n
  • links[i] contains neither i nor duplicates
  • The graph has no cycles
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsModule Build Order MediumCourse Enrollment Queue MediumDo the Links Form a Tree MediumBest Roots for a Tree MediumIsolated Groups in a Network Medium
loading Python…
Input
links=[[1, 2], [2, 3], [3], []]
Expected
[[0, 1, 3], [0, 2, 3], [0, 1, 2, 3]]

Run checks the first 3 tests in your browser. Submit checks all 72 tests on the server, hidden ones included.