File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ public class App {
4
+
5
+ public static void bfs (byte [][] a ,int vertices ,int source ){ //passing adjacency matrix and no of vertices
6
+ byte []b =new byte [vertices ]; //flag container containing status of each vertices
7
+ Arrays .fill (b ,(byte )-1 ); //status initialization
8
+ /* code status
9
+ -1 = ready
10
+ 0 = waiting
11
+ 1 = processed */
12
+
13
+ Queue <Integer > st =new LinkedList <>(); //operational stack
14
+ st .add (source ); //assigning source
15
+ while (!st .isEmpty ()){
16
+ b [st .peek ()]=(byte )0 ; //assigning waiting status
17
+ System .out .println (st .element ());
18
+ int pop =st .element ();
19
+ b [pop ]=(byte )1 ; //assigning processed status
20
+ st .remove (); //removing head of the queue
21
+ for (int i =0 ;i <vertices ;i ++){
22
+ if (a [pop ][i ]!=0 && b [i ]!=(byte )0 && b [i ]!=(byte )1 ){
23
+ st .add (i );
24
+ b [i ]=(byte )0 ; //assigning waiting status
25
+ }}}
26
+ }
27
+
28
+
29
+ public static void main (String args []){
30
+ Scanner in =new Scanner (System .in );
31
+ int vertices =in .nextInt (),source =in .nextInt ();
32
+ byte [][]a =new byte [vertices ][vertices ];
33
+ //initially all elements of a are initialized with value zero
34
+
35
+ for (int i =0 ;i <vertices ;i ++){
36
+ int size =in .nextInt ();
37
+ for (int j =0 ;j <size ;j ++){
38
+ a [i ][in .nextInt ()]=1 ; //taking adjacency entries by assigning 1
39
+ }
40
+ }
41
+ bfs (a ,vertices ,source ); //function call
42
+ }}
You can’t perform that action at this time.
0 commit comments