There are N
rooms and you start in room 0
. Each room has a distinct number in 0, 1, 2, ..., N-1
, and each room may have some keys to access the next room.
Formally, each room i
has a list of keys rooms[i]
, and each key rooms[i][j]
is an integer in [0, 1, ..., N-1]
where N = rooms.length
. A key rooms[i][j] = v
opens the room with number v
.
Initially, all the rooms start locked (except for room 0
).
You can walk back and forth between rooms freely.
Return true
if and only if you can enter every room.
Example 1:
Input: [[1],[2],[3],[]] Output: true Explanation: We start in room 0, and pick up key 1. We then go to room 1, and pick up key 2. We then go to room 2, and pick up key 3. We then go to room 3. Since we were able to go to every room, we return true.
Example 2:
Input: [[1,3],[3,0,1],[2],[0]] Output: false Explanation: We can't enter the room with number 2.
Note:
1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
- The number of keys in all rooms combined is at most
3000
.
钥匙和房间。
有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。
在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。
最初,除 0 号房间外的其余所有房间都被锁住。
你可以自由地在房间之间来回走动。
如果能进入每个房间返回 true,否则返回 false。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/keys-and-rooms
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道图论/遍历的题,问是否能访问到每个房间,也就是在问是否能访问到图上的每个点。这道题BFS和DFS都能做,都需要一个额外数组记录某个房间是否有被访问过以避免死循环。
时间O(n)
空间O(n)
Java实现 - BFS
1 class Solution { 2 public boolean canVisitAllRooms(List<List<Integer>> rooms) { 3 // 房间的个数 4 int len = rooms.size(); 5 boolean[] visited = new boolean[len]; 6 Queue<Integer> queue = new LinkedList<>(); 7 queue.offer(0); 8 while (!queue.isEmpty()) { 9 int cur = queue.poll(); 10 if (visited[cur] == true) { 11 continue; 12 } 13 visited[cur] = true; 14 len--; 15 List<Integer> list = rooms.get(cur); 16 for (int i : list) { 17 queue.offer(i); 18 } 19 } 20 // 如果每个房间都看过了最后应该是0 21 return len == 0; 22 } 23 }
Java实现 - DFS
1 class Solution { 2 public boolean canVisitAllRooms(List<List<Integer>> rooms) { 3 int len = rooms.size(); 4 boolean[] visited = new boolean[len]; 5 Stack<Integer> stack = new Stack<>(); 6 stack.push(0); 7 visited[0] = true; 8 len--; 9 while (!stack.isEmpty()) { 10 int cur = stack.pop(); 11 for (int i : rooms.get(cur)) { 12 if (visited[i] == false) { 13 stack.add(i); 14 visited[i] = true; 15 len--; 16 } 17 } 18 } 19 return len == 0; 20 } 21 }