Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
735 B
3
Indexable
Never
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean[] visited = new boolean[rooms.size()];

        dfs(0, visited, rooms);

        for (int i = 0; i < visited.length; i++) {
            if (visited[i] == false) {
                return false;
            }
        }

        return true;
    }

    private void dfs(int node, boolean[] visited, List<List<Integer>> rooms) {
        if (visited[node]) {
            return;
        }

        List<Integer> neighbors = rooms.get(node);

        if (neighbors == null) {
            return;
        }

        visited[node] = true;

        for (Integer neighbor : neighbors) {
            dfs(neighbor, visited, rooms);
        }
    }
}
Leave a Comment