Keys and Rooms

Given rooms and the keys inside each room, return true if all rooms can be visited starting from room 0. Pattern focus: Visited set. Use a set to avoid revisiting rooms while exploring reachable keys.

Input Format

rooms = list of key lists

Output Format

true if every room can be visited

Constraints

  • 1 <= rooms.length <= 10^5
  • Room keys are numbered from 0 to n-1.

Examples

Example 1:

Input:

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

Output:

true

Explanation:

Each room unlocks the next room, so all rooms are reachable.

Example 2:

Input:

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

Output:

false

Explanation:

Room 2 cannot be reached from room 0.

Example 3:

Input:

rooms = [[]]

Output:

true

Explanation:

There is only one room and it is already visited.

Loading...
Keys and Rooms - Graph Traversal DSA Problem