All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0801_0900.s0841_keys_and_rooms.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0801_0900.s0841_keys_and_rooms;

// #Medium #Depth_First_Search #Breadth_First_Search #Graph

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Solution {
    public boolean canVisitAllRooms(List> rooms) {
        Set visited = new HashSet<>();
        visited.add(0);
        TreeSet treeSet = new TreeSet<>(rooms.get(0));
        while (!treeSet.isEmpty()) {
            Integer key = treeSet.pollFirst();
            if (!visited.add(key)) {
                continue;
            }
            if (visited.size() == rooms.size()) {
                return true;
            }
            treeSet.addAll(rooms.get(key));
        }
        return visited.size() == rooms.size();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy