import java.util.Iterator; import java.util.LinkedList; class Graph { private int V; private LinkedList<Integer>[] adj; Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList<>(); } void addEdge(int u, int v) { adj[u].add(v); } void BFS(int s) { boolean vis[] = new boolean[V]; LinkedList<Integer> queue = new LinkedList<>(); vis[s] = true; queue.add(s); while (!queue.isEmpty()) { s = queue.poll(); System.out.print(s + " "); Iterator<Integer> i = adj[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!vis[n]) { vis[n] = true; queue.add(n); } } } } public static void main(String args[]) { Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(3, 2); g.addEdge(5, 2); g.addEdge(3, 5); g.addEdge(3, 4); g.addEdge(4, 6); g.addEdge(6, 3); g.addEdge(6, 7); g.addEdge(7, 1); System.out.print("BFS traversal from vertex 0 is: "); g.BFS(0); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter