-
Notifications
You must be signed in to change notification settings - Fork 0
/
Keys and Rooms.java
24 lines (22 loc) · 997 Bytes
/
Keys and Rooms.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
https://leetcode.com/problems/keys-and-rooms/
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] seen = new boolean[rooms.size()];
seen[0] = true;
Stack<Integer> stack = new Stack();
stack.push(0);
//At the beginning, we have a todo list "stack" of keys to use.
//'seen' represents at some point we have entered this room.
while (!stack.isEmpty()) { // While we have keys...
int node = stack.pop(); // Get the next key 'node'
for (int nei: rooms.get(node)) // For every key in room # 'node'...
if (!seen[nei]) { // ...that hasn't been used yet
seen[nei] = true; // mark that we've entered the room
stack.push(nei); // add the key to the todo list
}
}
for (boolean v: seen) // if any room hasn't been visited, return false
if (!v) return false;
return true;
}
}