Skip to content

Instantly share code, notes, and snippets.

@BiruLyu
Last active May 29, 2018 01:25
Show Gist options
  • Save BiruLyu/2ba444d3f6da5babe95d3dda31db0da5 to your computer and use it in GitHub Desktop.
Save BiruLyu/2ba444d3f6da5babe95d3dda31db0da5 to your computer and use it in GitHub Desktop.
#BFS
class Solution {
int count = 0;
int N = 0;
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
if (rooms == null || rooms.size() < 1) return true;
int n = rooms.size();
count = n;
N = n;
boolean[] visited = new boolean[n];
Set<Integer> canReach = new HashSet<>();
visited[0] = true;
canReach.add(0);
Queue<Integer> q = new LinkedList<>();
q.offer(0);
while (!q.isEmpty()) {
int cur = q.poll();
visited[cur] = true;
canReach.add(cur);
if (canReach.size() == N) {
return true;
}
for (int i : rooms.get(cur)) {
if (!visited[i]) {
q.offer(i);
}
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment