xiutianxiudi

Leetcode 841. Keys and Rooms

Sep 17th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.77 KB | None | 0 0
  1. class Solution {
  2.     public boolean canVisitAllRooms(List<List<Integer>> rooms) {
  3.         if(rooms == null || rooms.size() == 0) {
  4.             return true;
  5.         }
  6.  
  7.         int n = rooms.size();
  8.  
  9.         int visitedCount = 1;
  10.         boolean[] visited = new boolean[n];
  11.         visited[0] = true;
  12.  
  13.         Queue<Integer> q = new LinkedList<Integer>();
  14.         for(int nextKey : rooms.get(0)) {
  15.             if(!visited[nextKey]) {
  16.                 q.add(nextKey);
  17.                 visited[nextKey] = true;
  18.                 visitedCount++;
  19.             }
  20.         }
  21.  
  22.         while(visitedCount < n && !q.isEmpty()) {
  23.             int key = q.remove();
  24.             for(int nextKey : rooms.get(key)) {
  25.                 if(!visited[nextKey]) {
  26.                     q.add(nextKey);
  27.                     visited[nextKey] = true;
  28.                     visitedCount++;
  29.                 }
  30.             }
  31.         }
  32.         return visitedCount == n;
  33.     }
  34. }
Add Comment
Please, Sign In to add comment