mediumGraphDFSGraphs

Keys and Rooms

mediumTime: O(V+E)Space: O(V)

Signals to notice

can you visit all rooms starting from room 0keys in rooms unlock other roomsreachability

Brute force first

No simpler alternative — graph traversal is the natural approach. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

BFS or DFS from room 0. Each room you enter gives you keys to other rooms. Track visited rooms. If all rooms are visited, return true. where E = total keys. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

Starting from room 0 with its keys, you can only enter rooms you have keys to. It's a reachability problem — can you reach all rooms from room 0 via the key graph? If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not tracking visited rooms — without it, you could enter the same room multiple times and loop infinitely if there are cycles in the key structure. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Graphs Pattern