SHARE
TWEET

Leetcode 841. Keys and Rooms

xiutianxiudi Sep 17th, 2019 (edited) 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top