841. Keys and Rooms Medium

@problem@discussion
#Depth-First Search#Breadth-First Search#Graph



1/**
2 * [841] Keys and Rooms
3 *
4 * There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
5 * When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
6 * Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
7 *  
8 * Example 1:
9 * 
10 * Input: rooms = [[1],[2],[3],[]]
11 * Output: true
12 * Explanation: 
13 * We visit room 0 and pick up key 1.
14 * We then visit room 1 and pick up key 2.
15 * We then visit room 2 and pick up key 3.
16 * We then visit room 3.
17 * Since we were able to visit every room, we return true.
18 * 
19 * Example 2:
20 * 
21 * Input: rooms = [[1,3],[3,0,1],[2],[0]]
22 * Output: false
23 * Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
24 * 
25 *  
26 * Constraints:
27 * 
28 * 	n == rooms.length
29 * 	2 <= n <= 1000
30 * 	0 <= rooms[i].length <= 1000
31 * 	1 <= sum(rooms[i].length) <= 3000
32 * 	0 <= rooms[i][j] < n
33 * 	All the values of rooms[i] are unique.
34 * 
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/keys-and-rooms/
39// discuss: https://leetcode.com/problems/keys-and-rooms/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44    pub fn can_visit_all_rooms(rooms: Vec<Vec<i32>>) -> bool {
45        false
46    }
47}
48
49// submission codes end
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_841() {
57    }
58}
59


Back
© 2025 bowen.ge All Rights Reserved.