#841

Keys and Rooms

Medium
Depth-First SearchBreadth-First SearchGraph TheoryGraph TraversalDepth-First SearchBreadth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses Depth-First Search (DFS) or Breadth-First Search (BFS) to efficiently explore the rooms. By leveraging a stack or queue, we can systematically visit rooms without redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a stack or queue starting with room 0 and a visited list to track visited rooms.
  2. 2Step 2: While there are rooms to explore, pop a room from the stack/queue, mark it as visited, and add any unvisited rooms accessible via keys found in the current room.
  3. 3Step 3: Once all reachable rooms are visited, check if all rooms have been visited.
solution.py11 lines
1# Full working Python code
2class Solution:
3    def canVisitAllRooms(self, rooms):
4        visited = [False] * len(rooms)
5        stack = [0]
6        while stack:
7            room = stack.pop()
8            if not visited[room]:
9                visited[room] = True
10                stack.extend(rooms[room])
11        return all(visited)

Complexity note: This complexity is linear because we visit each room once and process each key found in the rooms, leading to a direct relationship with the number of rooms.

  • 1Using DFS/BFS allows efficient room exploration.
  • 2Tracking visited rooms prevents cycles and redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.