Skip to content

Commit 8ef3d70

Browse files
author
Mayank Kumar Jha
authored
bfs.java
1 parent 63726a9 commit 8ef3d70

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

bfs.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}}

0 commit comments

Comments
 (0)