forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeysAndRooms.java
More file actions
25 lines (22 loc) · 739 Bytes
/
KeysAndRooms.java
File metadata and controls
25 lines (22 loc) · 739 Bytes
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
class Solution {
// TC : O(n2)
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
Set<Integer> visitedRoomIDs = new HashSet<>();
Queue<Integer> qu =new LinkedList<>();
qu.offer(0);
visitedRoomIDs.add(0);
while(!qu.isEmpty()){
int size = qu.size();
while(size-->0){
Integer head = qu.poll();
for(Integer nextRoomId: rooms.get(head)){
if(!visitedRoomIDs.contains(nextRoomId)){
qu.offer(nextRoomId);
visitedRoomIDs.add(nextRoomId);
}
}
}
}
return rooms.size() == visitedRoomIDs.size();
}
}