JavaAlgorithms/data_structures/Graphs/bfs.java

63 lines
1.8 KiB
Java
Raw Normal View History

2017-03-17 22:01:25 +08:00
import java.util.*;
/**
* Implementation of a Breadth First Search
2017-07-10 07:29:00 +08:00
*
* @author Unknown
*
*/
public class bfs{
2017-07-10 07:29:00 +08:00
/**
2017-07-10 07:29:00 +08:00
* The BFS implemented in code to use.
*
* @param a Structure to perform the search on a graph, adjacency matrix etc.
* @param vertices The vertices to use
* @param source The Source
*/
public static void bfsImplement(byte [][] a,int vertices,int source){ //passing adjacency matrix and no of vertices
2017-03-17 22:01:25 +08:00
byte []b=new byte[vertices]; //flag container containing status of each vertices
Arrays.fill(b,(byte)-1); //status initialization
2017-07-10 07:29:00 +08:00
/* code status
2017-03-17 22:01:25 +08:00
-1 = ready
0 = waiting
1 = processed */
2017-07-10 07:29:00 +08:00
Stack st = new Stack(vertices); //operational stack
st.push(source); //assigning source
2017-03-17 22:01:25 +08:00
while(!st.isEmpty()){
b[st.peek()]=(byte)0; //assigning waiting status
System.out.println(st.peek());
int pop=st.peek();
2017-03-17 22:01:25 +08:00
b[pop]=(byte)1; //assigning processed status
2017-07-10 07:29:00 +08:00
st.pop(); //removing head of the queue
2017-03-17 22:01:25 +08:00
for(int i=0;i<vertices;i++){
if(a[pop][i]!=0 && b[i]!=(byte)0 && b[i]!=(byte)1 ){
st.push(i);
2017-03-17 22:01:25 +08:00
b[i]=(byte)0; //assigning waiting status
}}}
}
2017-07-10 07:29:00 +08:00
/**
2017-07-10 07:29:00 +08:00
* The main method
*
* @param args Command line arguments
*/
2017-03-17 22:01:25 +08:00
public static void main(String args[]){
Scanner in=new Scanner(System.in);
int vertices=in.nextInt(),source=in.nextInt();
byte [][]a=new byte [vertices][vertices];
//initially all elements of a are initialized with value zero
2017-07-10 07:29:00 +08:00
2017-03-17 22:01:25 +08:00
for(int i=0;i<vertices;i++){
2017-07-10 07:29:00 +08:00
int size =in.nextInt();
2017-03-17 22:01:25 +08:00
for(int j=0;j<size;j++){
a[i][in.nextInt()]=1; //taking adjacency entries by assigning 1
}
}
bfsImplement(a,vertices,source); //function call
in.close();
}
}