841. Keys and Rooms
Question
There are
n
rooms labeled from0
ton - 1
and all the rooms are locked except for room0
. 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
whererooms[i]
is the set of keys that you can obtain if you visited roomi
, returntrue
if you can visit all the rooms, orfalse
otherwise.
Solution
BFS,创建一个数组记录房间是否被访问。(用DFS搜素亦可。)
如果钥匙对应的房间已经访问过则跳过。
如果未访问过则记录为已访问并加入队列。
最后遍历一次访问状态,如果有没访问过的房间则返回false。反之返回true。
Code
1 | class Solution { |
841. Keys and Rooms