11package graphs ;
22import java .util .*;
33
4- /*
5- * Problem Title :-> Implement BFS Algorithm of Traversal of Graph.
6- */
4+ // Problem Title -> Implement BFS Algorithm of Traversal of Graph.
75public class Graph_Problem_02 {
86 // No. of vertices.
9- private int V ;
7+ private final int V ;
8+
109 // Adjacency List
11- private LinkedList <Integer >[] adj ;
10+ private final LinkedList <Integer >[] adj ;
1211
1312 @ SuppressWarnings ({ "unchecked" , "rawtypes" })
1413 // Constructor
@@ -26,13 +25,16 @@ void addEdge(int v, int w) {
2625
2726 // prints BFS traversal from a given source s
2827 void BFS (int s ) {
29- // Mark all the verices as not visited(By Default set as false)
30- boolean visited [] = new boolean [V ];
28+ // Mark all the vertices as not visited(By Default set as false)
29+ boolean [] visited = new boolean [V ];
3130
3231 // Create a queue for BFS
3332 LinkedList <Integer > queue = new LinkedList <>();
34-
33+
34+ // mark visited array as true
3535 visited [s ] = true ;
36+
37+ // add it to queue
3638 queue .add (s );
3739
3840 while (queue .size () != 0 ) {
@@ -41,12 +43,9 @@ void BFS(int s) {
4143 System .out .println (s + " " );
4244
4345 // Get all adjacent vertices of the dequeued vertex s.
44- // If a adjacent has not been visited,
45- // then mark it visited & enqueue it.
46- Iterator <Integer > i = adj [s ].listIterator ();
47- while (i .hasNext ()) {
48- int n = i .next ();
49- if (!visited [n ]) {
46+ for (int n : adj [s ]) {
47+ // If an adjacent has not been visited, then mark it visited & enqueue it.
48+ if (!visited [n ]) {
5049 visited [n ] = true ;
5150 queue .add (n );
5251 }
@@ -55,21 +54,25 @@ void BFS(int s) {
5554 }
5655
5756 public static void main (String [] args ) {
58-
57+
58+ // Taking input
5959 System .out .println ("Enter number of vertices and edges" );
6060 Scanner sc = new Scanner (System .in );
6161
6262 int v = sc .nextInt ();
6363 int e = sc .nextInt ();
64-
64+ int s = sc .nextInt ();
65+
66+ // invoking the class by making object
6567 Graph_Problem_02 g = new Graph_Problem_02 (v );
66-
68+
6769 for (int i = 0 ; i < e ; i ++) {
6870 v = sc .nextInt ();
6971 e = sc .nextInt ();
7072 g .addEdge (v , e );
7173 }
72-
74+
7375 sc .close ();
76+ g .BFS (s );
7477 }
7578}
0 commit comments