MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / BfsTraversal

Class BfsTraversal

Java/BfsTraversal.java:4–58  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2import java.util.*;
3
4public class BfsTraversal {
5 private int node; /* total number number of nodes in the graph */
6 private LinkedList<Integer> adj[]; /* adjacency list */
7 private Queue<Integer> que; /* maintaining a queue */
8
9 BfsTraversal(int v) {
10 node = v;
11 adj = new LinkedList[node];
12 for (int i = 0; i < v; i++) {
13 adj[i] = new LinkedList<Integer>();
14 }
15 que = new LinkedList<Integer>();
16 }
17
18 void insertEdge(int v, int w) {
19 adj[v].add(w);
20 }
21
22 void BFS(int n) {
23 boolean nodes[] = new boolean[node]; /* initialize boolean array for holding the data */
24 int a = 0;
25 nodes[n] = true;
26 que.add(n); /* root node is added to the top of the queue */
27 while (que.size() != 0) {
28 n = que.poll(); /* remove the top element of the queue */
29 System.out.print(n + " "); /* print the top element of the queue */
30 for (int i = 0; i < adj[n].size(); i++) {
31 a = adj[n].get(i);
32 if (!nodes[a]) /* only insert nodes into queue if they have not been explored already */
33 {
34 nodes[a] = true;
35 que.add(a);
36 }
37 }
38 }
39 }
40
41 public static void main(String args[]) {
42 Scanner sc = new Scanner(System.in);
43 System.out.println("Enter number of vertices");
44 int ve = sc.nextInt();
45 BfsTraversal graph = new BfsTraversal(ve);
46 System.out.println("Enter number of edges");
47 int e = sc.nextInt();
48 for (int i = 0; i < e; i++) {
49 System.out.println("Enter starting vertex of the edge " + i);
50 int u = sc.nextInt();
51 System.out.println("Enter ending vertex of the edge " + i);
52 int v = sc.nextInt();
53 graph.insertEdge(u, v);
54 }
55 System.out.println("Breadth First Traversal for the graph is:");
56 graph.BFS(0);
57 }
58}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected