Hello!! Today is the second of 365 days of covering Algo questions and concepts! We're going to go into graphs today by solving a Leetcode question.
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.
Examples:
Example 1:
Input: [[1],[2],[3],[]]
Output: true
Explanation: We start in room 0, and pick up key 1.
We then go to room 1 and pick up key 2.
We then go to room 2 and pick up key 3.
We then go to room 3.
Since we were able to go to every room, we return true.
Example 2:
Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.
Breaking this down:
Reading through the question the first idea I had was to iterate through the input array (R) of rooms, but iterating through the input array won't work because we can only access rooms if we have the keys.
On second thought if we think of it as a graph, we can see that the rooms are like vertices(or nodes) and the keys are like edges.
In this case, we can use graph traversal methods like a breadth-first search (BFS) queue or a depth-first search (DFS) stack approach. Firstly we would have to keep track of the rooms we have visited by creating a visitedRoom variable which is going to be a set, so as not to have duplicates
Secondly, we add our starting point to this set(visitedRoom), then we goona store in the stack all the rooms we have access to.
While our !stack.empty() we can try to get into other rooms by getting the keys from the rooms we have access to
Once our stack runs empty, we can just check to see if the set size((visitedRoom)) is the same as the length of R and return the answer.
Implementation: you can whichever language you are comfortable with, am going with JS.
var canVisitAllRooms = function(rooms) {
let visitedRoom = new Set(), stack= [];
visitedRoom.add(0)
stack.push(0);
while(stack.length){
let keys=rooms[stack.pop()]
for(let k of keys){
if(!visitedRoom.has(k)){
visitedRoom.add(k)
stack.push(k)
}
}
}
return visitedRoom.size == rooms.length
};
Conclusion
Please post your creative solutions in the comments section below. If you have a challenge you'd like to see done, write it in the comments below and it might just get done!
Thanks for stopping by.