A museum has rooms 0 .. n-1 joined by two-way doors. The kiosk at the entrance prints a walking route to any exhibit: the rooms to walk through, using as few doors as possible.
Write museum_route(n, doors, entrance, exhibit) -> list[int]:
doorsis a list of pairs(a, b). Doors may repeat, and(a, a)may appear.- Return a route that starts at
entrance, ends atexhibit, has a door between each pair of consecutive rooms, and uses the fewest doors. Any shortest route is fine. - If
entrance == exhibit, return[entrance]; if the exhibit can't be reached,[].
doors = [(0, 1), (1, 2), (2, 5), (0, 3), (3, 4), (4, 5), (1, 4), (6, 7)]
museum_route(8, doors, 0, 5) # [0, 1, 2, 5] or [0, 1, 4, 5] or [0, 3, 4, 5] (3 doors)
museum_route(8, doors, 0, 0) # [0]
museum_route(8, doors, 0, 7) # []
Up to 10**5 rooms and 2 * 10**5 doors. One test is a 50,000-room corridor, so rebuild the route with a loop, not recursion.
⭐ Bonus: a speed test with 100,000 rooms and 200,000 doors earns a star in O(rooms + doors).
Show hint
BFS from the entrance, recording parent[v] = u when you first reach a room. Then walk the parents back from the exhibit and reverse.