-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeysAndRooms.java
More file actions
84 lines (74 loc) · 2.5 KB
/
KeysAndRooms.java
File metadata and controls
84 lines (74 loc) · 2.5 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package Algorithms.Graphs;
import java.util.HashSet;
import java.util.List;
import java.util.Stack;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 01 May 2025
*/
public class KeysAndRooms {
public static void main(String[] args) {
int[][] rooms = {{1}, {2}, {3}, {}};
System.out.println(canVisitAllRooms(rooms)); // Output: true
}
/**
APPROACH:
---------
1) Given AdjacentList Graph
2) Check if all nodes are connected
3) So, we can use adjLst dfs or unionFind
4) In adjLst, entryPoint = 0
NOTE:
-----
UnionFind is failing for [[1],[],[0,3],[1]] because we can't go after 1
and [[2],[],[1]] cause we only get room1 key from room0 and room1 key from room2
*/
public static boolean canVisitAllRooms(int[][] rooms) {
boolean[] visited = new boolean[rooms.length];
visited[0] = true;
dfs(rooms, 0, visited);
for (boolean room : visited) if (!room) return false;
return true;
// Arrays.stream(visited).allMatch(v -> v); ---- won't work for boolean[]
}
public static void dfs(int[][] rooms, int room, boolean[] visited) {
for (int key : rooms[room]) {
if (!visited[key]) {
visited[key] = true;
dfs(rooms, key, visited);
}
}
}
public boolean canVisitAllRooms2(List<List<Integer>> rooms) {
HashSet<Integer> visited = new HashSet<>();
dfs(rooms, 0 , visited);
return visited.size() == rooms.size();
}
public void dfs(List<List<Integer>> rooms, int currentRoom , HashSet<Integer> visited){
visited.add(currentRoom);
for( int key : rooms.get(currentRoom)){
if(!visited.contains(key)){
dfs(rooms, key , visited);
}
}
}
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] seen = new boolean[rooms.size()];
seen[0] = true;
Stack<Integer> stack = new Stack<>();
stack.push(0);
int currentCount = 1;
while (!stack.isEmpty()) {
int node = stack.pop();
for (int nei: rooms.get(node)) {
if (!seen[nei]) {
seen[nei] = true;
currentCount++;
if(currentCount==rooms.size()) return true;
stack.push(nei);
}
}
}
return false; // or currentCount == rooms.size()
}
}