g0801_0900.s0841_keys_and_rooms.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0801_0900.s0841_keys_and_rooms;
// #Medium #Depth_First_Search #Breadth_First_Search #Graph
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Solution {
public boolean canVisitAllRooms(List> rooms) {
Set visited = new HashSet<>();
visited.add(0);
TreeSet treeSet = new TreeSet<>(rooms.get(0));
while (!treeSet.isEmpty()) {
Integer key = treeSet.pollFirst();
if (!visited.add(key)) {
continue;
}
if (visited.size() == rooms.size()) {
return true;
}
treeSet.addAll(rooms.get(key));
}
return visited.size() == rooms.size();
}
}