Skip to content

Commit c271ea2

Browse files
authored
Updated Keys and Rooms.java to iterative version
1 parent 1948214 commit c271ea2

File tree

1 file changed

+13
-20
lines changed

1 file changed

+13
-20
lines changed

Medium/Keys and Rooms.java

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,19 @@
11
class Solution {
2-
int[] keys;
32
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
4-
keys = new int[rooms.size()];
5-
keys[0] = 1;
6-
7-
dfs(rooms, 0);
8-
9-
for (int key : keys) {
10-
if (key == 0) {
11-
return false;
12-
}
13-
}
14-
15-
return true;
16-
}
17-
18-
private void dfs(List<List<Integer>> rooms, int k) {
19-
for (int key : rooms.get(k)) {
20-
if (keys[key] == 0) {
21-
keys[key]++;
22-
dfs(rooms, key);
3+
Stack<Integer> stack = new Stack<>();
4+
Set<Integer> set = new HashSet<>();
5+
set.add(0);
6+
stack.add(0);
7+
while (!stack.isEmpty()) {
8+
int keyPopped = stack.pop();
9+
List<Integer> keys = rooms.get(keyPopped);
10+
for (Integer key : keys) {
11+
if (!set.contains(key)) {
12+
stack.push(key);
13+
set.add(key);
14+
}
2315
}
2416
}
17+
return set.size() == rooms.size();
2518
}
2619
}

0 commit comments

Comments
 (0)