Last active
May 29, 2018 01:25
-
-
Save BiruLyu/2ba444d3f6da5babe95d3dda31db0da5 to your computer and use it in GitHub Desktop.
#BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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