GraphBFS¶
Utility class to perform Breadth-First Search (BFS) on a graph. BFS is a graph traversal algorithm that explores nodes level by level. The algorithm works as follows:
- Start from a source node
- Visit all its neighbors
- Then visit neighbors of neighbors
Use Cases:
- Shortest path in unweighted graph
- Level order traversal
- Finding connected components Time Complexity: O(V + E) Space Complexity: O(V)
bfs¶
Performs BFS traversal from a given source node.
List<Integer> bfs(Map<Integer, List<Integer>> graph, int start) {
List<Integer> result = new ArrayList<>();
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited.add(start);
while (!queue.isEmpty()) {
int node = queue.poll();
result.add(node);
for (int neighbor : graph.getOrDefault(node, Collections.emptyList())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
return result;
}