progress

~/problems / Graphs / BFS / multi-source BFS

Museum: fewest doors to an exhibit

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

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]:

  • doors is a list of pairs (a, b). Doors may repeat, and (a, a) may appear.
  • Return a route that starts at entrance, ends at exhibit, 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)   # []
Eight museum rooms: rooms 0, 1, 2 above rooms 3, 4, 5 joined like a ladder, with a highlighted three-door route 0, 1, 2, 5; rooms 6 and 7 form a separate pair unreachable from the entrance.

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.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc