Ariadne's thread
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- lists
- loops
Problem
Before Theseus goes into the labyrinth of Crete, Ariadne gives him a ball of thread so he can find his way back. She wants to know how many different paths lead from the entrance to the Minotaur without going through the same room twice: where the thread has already been, Theseus doesn't go in again.
Write a function that takes doors, a list of lists of whole numbers. Rooms are numbered from 0, and doors[i] holds the rooms you can go to from room i. Doors work both ways: if 2 is in doors[0], 0 is in doors[2]. No door is listed twice and no door leads from a room to itself. The entrance is room 0 and the Minotaur is in the last room. There is at least one room and at most 8.
Return a whole number: how many paths start at the entrance, end in the Minotaur's room and repeat no room. Two paths are different if they don't go through the same rooms in the same order.
With [[1, 2], [0, 2, 3], [0, 1, 3], [1, 2]] there are 4: 0-1-3, 0-2-3, 0-1-2-3 and 0-2-1-3. With [[1], [0], []] room 2 has no doors, so there are none: 0. If the entrance is the Minotaur's room, the only path is staying there: 1.
Examples
The example
[[1, 2], [0, 2, 3], [0, 1, 3], [1, 2]] → 4
The Minotaur's room has no doors
[[1], [0], []] → 0
A corridor
[[1], [0, 2], [1]] → 1
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def paths(doors):
passJavaScript
function paths(doors) {
}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.