Skip to main content
Back to problems
Leetcode
Medium
Graphs
Sets
Stacks
Queues
Google
841. Keys and Rooms

Determine whether all rooms can be entered starting from room 0 using the keys found along the way.

Acceptance 0%
Problem Statement

Keys and Rooms

You are given a list of rooms. Each room may contain keys to other rooms. You start in room 0, and initially only room 0 is unlocked.

Whenever you enter a room, you can collect every key inside it and use those keys to unlock additional rooms. The task is to determine whether it is possible to visit every room in the building by repeatedly taking keys from rooms you have already entered.

Return true if every room can be visited, otherwise return false.

Notes

  • You may enter a room only if you already have its key.
  • A key can be reused any number of times.
  • The order in which you explore rooms does not matter as long as all reachable rooms are eventually visited.

Input Format

  • rooms: a list where rooms[i] contains the keys found in room i.
  • Room numbering starts at 0.
  • Each key is an integer referring to another room index.

Output Format

  • Return a boolean value.
  • true if all rooms are reachable from room 0.
  • false otherwise.

Constraints

  • 1 <= rooms.length
  • Each rooms[i] is a list of room indices.
  • Room indices are valid for the given input.
  • Keys may repeat across rooms.
Examples
Sample cases returned by the problem API.

Example 1

Input

rooms = [[1],[2],[3],[]]

Output

true

Explanation

Starting from room 0, you get key 1, then from room 1 key 2, then from room 2 key 3, so every room can be visited.

Example 2

Input

rooms = [[1,3],[3,0,1],[2],[0]]

Output

false

Explanation

Room 0 lets you enter rooms 1 and 3, but no path reaches room 2. Therefore not all rooms are visitable.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.