import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class Main {
static void bfs(Map<Integer, List<Integer> > graph,
int root)
{
// Set to keep track of visited vertices
boolean[] visited = new boolean[graph.size()];
// Queue for BFS traversal
Queue<Integer> queue = new ArrayDeque<>();
// Enqueue the root vertex
queue.add(root);
// Mark root as visited
visited[root] = true;
// BFS traversal
while (!queue.isEmpty()) {
// Dequeue a vertex from the queue
int vertex = queue.poll();
System.out.print(vertex + " ");
// Visit all adjacent vertices of the dequeued
// vertex
for (int neighbour : graph.getOrDefault(
vertex, new ArrayList<>())) {
// If neighbour has not been visited, mark
// it as visited and enqueue it
if (!visited[neighbour]) {
visited[neighbour] = true;
queue.add(neighbour);
}
}
}
}
public static void main(String[] args)
{
// Create a map to use as an adjacency list
Map<Integer, List<Integer> > graph
= new HashMap<>();
// Define the edges
int[][] edges
= { { 0, 1 }, { 0, 2 }, { 0, 3 }, { 0, 4 },
{ 1, 5 }, { 2, 5 }, { 3, 6 }, { 4, 6 },
{ 5, 7 }, { 6, 7 } };
// Create the graph
for (int[] edge : edges) {
int a = edge[0];
int b = edge[1];
graph.computeIfAbsent(a, k -> new ArrayList<>())
.add(b);
graph.computeIfAbsent(b, k -> new ArrayList<>())
.add(a);
}
// Perform BFS starting from vertex 0
System.out.println("BFS starting from vertex 0:");
bfs(graph, 0);
}
}