Iterative DFS
Time O(rooms + keys) Space O(rooms)Stack starting with 0. Pop a room, push keys to unvisited rooms. Compare the visited count with n.
import java.util.*;
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
boolean[] seen = new boolean[rooms.size()];
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
seen[0] = true;
int visited = 1;
while (!stack.isEmpty()) {
for (int key : rooms.get(stack.pop())) {
if (seen[key]) continue;
seen[key] = true;
visited++;
stack.push(key);
}
}
return visited == rooms.size();
}
}Verdict: Directly the reachability question.