-
Notifications
You must be signed in to change notification settings - Fork 2
/
KeysAndRooms.java
58 lines (49 loc) · 1.17 KB
/
KeysAndRooms.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.algorithm.playground.leetcode.problems.lc800.lc840.lc841;
import java.util.LinkedList;
import java.util.List;
/**
* https://leetcode.com/problems/keys-and-rooms/description/
*/
public class KeysAndRooms {
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] seen = new boolean[rooms.size()];
dfs(rooms, seen, 0);
for (boolean b : seen) {
if (!b) {
return false;
}
}
return true;
}
private void dfs(List<List<Integer>> rooms, boolean[] visited, int idx) {
if (visited[idx]) {
return;
}
visited[idx] = true;
for (Integer i : rooms.get(idx)) {
dfs(rooms, visited, i);
}
}
}
class IterativeSolution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] seen = new boolean[rooms.size()];
int unvisited = seen.length;
LinkedList<Integer> stack = new LinkedList<>();
stack.push(0);
while (!stack.isEmpty() && unvisited > 0) {
Integer curr = stack.pop();
if (seen[curr]) {
continue;
}
for (Integer i : rooms.get(curr)) {
stack.push(i);
}
seen[curr] = true;
unvisited--;
}
return unvisited == 0;
}
}
}