-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKeysAndRooms.java
More file actions
57 lines (46 loc) · 1.46 KB
/
KeysAndRooms.java
File metadata and controls
57 lines (46 loc) · 1.46 KB
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
package graph;
import java.util.*;
/**
* Description: https://leetcode.com/problems/keys-and-rooms
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class KeysAndRooms {
public boolean canVisitAllRoomsV1(List<List<Integer>> rooms) {
int[] visited = new int[rooms.size()];
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
int count = 0;
while (!stack.isEmpty()) {
int current = stack.pop();
if (visited[current] == 0) {
stack.push(current);
visited[current] = 1;
for (int neighbor : rooms.get(current)) {
if (visited[neighbor] == 0) {
stack.push(neighbor);
}
}
} else if (visited[current] == 1) {
visited[current] = 2;
count++;
}
}
return count == rooms.size();
}
public boolean canVisitAllRoomsV2(List<List<Integer>> rooms) {
Set<Integer> visited = new HashSet<>();
Deque<Integer> stack = new LinkedList<>();
stack.push(0);
while (!stack.isEmpty()) {
int current = stack.pop();
if (visited.add(current)) {
for (int neighbor : rooms.get(current)) {
stack.push(neighbor);
}
}
}
return visited.size() == rooms.size();
}
}