841. Keys and Rooms (javascript solution)

cod3pineapple

codingpineapple

Posted on March 22, 2021

841. Keys and Rooms (javascript solution)

Description:

There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.

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. A key rooms[i][j] = v opens the room with number v.

Initially, all the rooms start locked (except for room 0).

You can walk back and forth between rooms freely.

Return true if and only if you can enter every room.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// DFS apprach
var canVisitAllRooms = function(rooms) {
    // Keep track of visited rooms
    const set = new Set();

    // Recursive dfs function to search rooms
    function dfs(index, rooms, set) {
        // Don't check this room if it has already been visited
        if(set.has(index)) return;
        // Add this room to the list of checked rooms
        set.add(index);
        // Check all the keys in this room
        for(const key of rooms[index]) {
            dfs(key, rooms, set);
        }
    }
    // Start at the first room
    dfs(0, rooms, set);

    // Check if all the rooms have been visited
    return set.size === rooms.length;
};
Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
cod3pineapple
codingpineapple

Posted on March 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related