Skip to content

Instantly share code, notes, and snippets.

@Allan-Gong
Created December 21, 2025 20:15
Show Gist options
  • Select an option

  • Save Allan-Gong/867274964a6fcc4709674a66f934e266 to your computer and use it in GitHub Desktop.

Select an option

Save Allan-Gong/867274964a6fcc4709674a66f934e266 to your computer and use it in GitHub Desktop.
BFS template
private List<String> bfs(Map<String, Set<String>> graph, Set<String> visited, String start) {
if (visited.contains(start)) return Collections.emptyList();
List<String> emails = new ArrayList<>();
Queue<String> queue = new LinkedList<>();
queue.offer(start);
visited.add(start);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String node = queue.poll();
emails.add(node);
Set<String> neighbors = graph.get(node);
for (String neighbor : neighbors) {
if (visited.contains(neighbor)) continue;
queue.offer(neighbor);
visited.add(neighbor);
}
}
}
return emails;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment