[LeetCode] 841. Keys and Rooms

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.

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.

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.

Example 1:
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.

Example 2:
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.

Constraints:
n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
All the values of rooms[i] are unique.

钥匙和房间。

有 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)

代码

BFS实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n = rooms.size();
int count = 1;
boolean[] visited = new boolean[n];
visited[0] = true;
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
while (!queue.isEmpty()) {
int cur = queue.poll();
for (int next : rooms.get(cur)) {
if (!visited[next]) {
queue.offer(next);
visited[next] = true;
count++;
}
}
}
return count == n;
}
}

DFS实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int count = 0;

public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n = rooms.size();
boolean[] visited = new boolean[n];
visited[0] = true;
count++;
dfs(rooms, visited, 0);
return count == n;
}

private void dfs(List<List<Integer>> rooms, boolean[] visited, int index) {
List<Integer> keys = rooms.get(index);
for (int next : keys) {
if (!visited[next]) {
visited[next] = true;
count++;
dfs(rooms, visited, next);
}
}
}
}

[LeetCode] 841. Keys and Rooms
https://shurui91.github.io/posts/4018564189.html
Author
Aaron Liu
Posted on
March 21, 2021
Licensed under