Created
December 21, 2025 20:15
-
-
Save Allan-Gong/867274964a6fcc4709674a66f934e266 to your computer and use it in GitHub Desktop.
BFS template
This file contains hidden or 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
| 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