Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public boolean canVisitAllRooms(List<List<Integer>> rooms) {
- if(rooms == null || rooms.size() == 0) {
- return true;
- }
- int n = rooms.size();
- int visitedCount = 1;
- boolean[] visited = new boolean[n];
- visited[0] = true;
- Queue<Integer> q = new LinkedList<Integer>();
- for(int nextKey : rooms.get(0)) {
- if(!visited[nextKey]) {
- q.add(nextKey);
- visited[nextKey] = true;
- visitedCount++;
- }
- }
- while(visitedCount < n && !q.isEmpty()) {
- int key = q.remove();
- for(int nextKey : rooms.get(key)) {
- if(!visited[nextKey]) {
- q.add(nextKey);
- visited[nextKey] = true;
- visitedCount++;
- }
- }
- }
- return visitedCount == n;
- }
- }
Add Comment
Please, Sign In to add comment