mediumGraphDFSGraphs

Keys and Rooms

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

Recognize the pattern

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

Brute force idea

If you approach Keys and Rooms in the most literal way possible, you get this: 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.

Better approach

A calmer way to see Keys and Rooms is this: 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.

Key invariant

The truth you want to protect throughout Keys and Rooms is this: 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.

Watch out for

The trap in Keys and Rooms usually looks like this: 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