题目
题目地址:https://leetcode-cn.com/problems/keys-and-rooms/
有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。
示例1:
1 2 3 4 5 6 7 8
| 输入: [[1],[2],[3],[]] 输出: true 解释: 我们从 0 号房间开始,拿到钥匙 1。 之后我们去 1 号房间,拿到钥匙 2。 然后我们去 2 号房间,拿到钥匙 3。 最后我们去了 3 号房间。 由于我们能够进入每个房间,我们返回 true。
|
示例2:
1 2 3
| 输入:[[1,3],[3,0,1],[2],[0]] 输出:false 解释:我们不能进入 2 号房间。
|
答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.jarome.leetcode.test1.summary;
import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set;
public class SolutionCanVisitAllRooms { public boolean canVisitAllRooms(List<List<Integer>> rooms) { Queue<Integer> queue = new LinkedList<>(); Set<Integer> cache = new HashSet<>(); List<Integer> zeroKeys = rooms.get(0); cache.add(0); for (Integer zeroKey : zeroKeys) { queue.offer(zeroKey); } while (!queue.isEmpty()) { Integer key = queue.poll(); if (cache.contains(key)) { continue; } List<Integer> keys = rooms.get(key); cache.add(key); if (keys != null) { for (Integer keyRoom : keys) { queue.offer(keyRoom); } } } return cache.size() == rooms.size(); }
}
|