Leetcode 841: Keys and Rooms

grid47
grid47
Exploring patterns and algorithms
Aug 14, 2024 6 min read

You are in a building with multiple rooms, each containing a set of keys to unlock other rooms. Initially, only the first room (room 0) is unlocked. You are tasked with determining whether you can visit all the rooms, starting from room 0. To enter a locked room, you must have its corresponding key, which can only be obtained by visiting other rooms.
Problem
Approach
Steps
Complexity
Input: You are given a 2D array 'rooms' where each rooms[i] contains a list of keys that can be obtained by visiting room i. Each key in the list unlocks a specific room in the building. Your goal is to check if it's possible to visit all rooms starting from room 0.
Example: Input: rooms = [[1, 2], [3], [3], [0]]
Constraints:
• 2 <= n <= 1000
• 0 <= rooms[i].length <= 1000
• 1 <= sum(rooms[i].length) <= 3000
• 0 <= rooms[i][j] < n
• All the values in rooms[i] are unique.
Output: Return true if it's possible to visit all rooms starting from room 0; otherwise, return false.
Example: Output: true
Constraints:
• The output should be a boolean value: true if all rooms can be visited, false otherwise.
Goal: The goal is to use a depth-first search (DFS) approach to simulate visiting each room and collecting keys. Keep track of which rooms have been visited, and ensure all rooms can be visited by collecting the necessary keys.
Steps:
• Step 1: Initialize a 'visited' array to track rooms that have been visited.
• Step 2: Use DFS starting from room 0, visiting all rooms that can be unlocked by the keys you collect.
• Step 3: Once all rooms are visited, return true. If there are any rooms that remain unvisited, return false.
Goal: Ensure the grid dimensions and input constraints are met as specified.
Steps:
• The number of rooms n is between 2 and 1000.
• Each room's list of keys contains between 0 and 1000 keys.
• The sum of all keys across rooms does not exceed 3000.
• The values in rooms[i] are unique and are valid indices (0 <= rooms[i][j] < n).
Assumptions:
• Each room contains a list of keys, which might allow access to other rooms.
• Starting at room 0, it is possible to gather keys to unlock additional rooms.
• The solution assumes that a DFS approach will help in determining whether all rooms can be visited.
Input: Input: [[1, 2], [3], [3], [0]]
Explanation: Starting from room 0, we can collect key 1 and visit room 1. From room 1, we collect key 3 and visit room 3. Finally, from room 3, we collect key 0 and can visit all rooms.

Input: Input: [[1,3],[3,0,1],[2],[0]]
Explanation: Here, starting from room 0, we collect key 1 and visit room 1. However, we cannot access room 2 because the only key to room 2 is located in room 2 itself, which remains locked.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus