|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Queue; |
| 7 | +import java.util.Set; |
| 8 | + |
| 9 | +/** |
| 10 | + * 841. Keys and Rooms |
| 11 | + * |
| 12 | + * There are N rooms and you start in room 0. |
| 13 | + * Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room. |
| 14 | + * Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. |
| 15 | + * A key rooms[i][j] = v opens the room with number v. |
| 16 | + * Initially, all the rooms start locked (except for room 0). |
| 17 | + * You can walk back and forth between rooms freely. |
| 18 | + * Return true if and only if you can enter every room. |
| 19 | + * |
| 20 | + * Example 1: |
| 21 | + * Input: [[1],[2],[3],[]] |
| 22 | + * Output: true |
| 23 | + * Explanation: |
| 24 | + * We start in room 0, and pick up key 1. |
| 25 | + * We then go to room 1, and pick up key 2. |
| 26 | + * We then go to room 2, and pick up key 3. |
| 27 | + * We then go to room 3. Since we were able to go to every room, we return true. |
| 28 | + * |
| 29 | + * Example 2: |
| 30 | + * Input: [[1,3],[3,0,1],[2],[0]] |
| 31 | + * Output: false |
| 32 | + * Explanation: We can't enter the room with number 2. |
| 33 | + * |
| 34 | + * Note: |
| 35 | + * 1 <= rooms.length <= 1000 |
| 36 | + * 0 <= rooms[i].length <= 1000 |
| 37 | + * The number of keys in all rooms combined is at most 3000. |
| 38 | + * */ |
| 39 | +public class _841 { |
| 40 | + public static class Solution1 { |
| 41 | + public boolean canVisitAllRooms(List<List<Integer>> rooms) { |
| 42 | + Set<Integer> unvisitedRooms = new HashSet<>(); |
| 43 | + for (int i = 1; i < rooms.size(); i++) { |
| 44 | + unvisitedRooms.add(i); |
| 45 | + } |
| 46 | + List<Integer> keys = rooms.get(0); |
| 47 | + Queue<Integer> queue = new LinkedList<>(); |
| 48 | + for (int key : keys) { |
| 49 | + queue.offer(key); |
| 50 | + } |
| 51 | + while (!queue.isEmpty()) { |
| 52 | + int size = queue.size(); |
| 53 | + for (int i = 0; i < size; i++) { |
| 54 | + int roomIndex = queue.poll(); |
| 55 | + unvisitedRooms.remove(roomIndex); |
| 56 | + for (int j = 0; j < rooms.get(roomIndex).size(); j++) { |
| 57 | + Integer nextRoom = rooms.get(roomIndex).get(j); |
| 58 | + if (unvisitedRooms.contains(nextRoom) && !queue.contains(nextRoom)) { |
| 59 | + queue.offer(nextRoom); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + return unvisitedRooms.isEmpty(); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments