Skip to main content

Breadth First Search Implementation in Java


Breadth First Search Implementation in Java

For Graph Class Design and DFS implementation please refer to below link:-

depth-first-search-implementation-in-java


 
/*

1. Pick a vertex.
2. Get Adjacent Vertex.
3. Insert in queue ( at tail)
4. Remove vertex from queue( head)
5. Do until no vertex left in a queue.

*/ 

void searchBFS()
 {
//this is how we define queue using LinkedList
  Queue<Character> queue=new LinkedList<Character>();
  
  queue.add(vertexlist[0].label);
  
  
 
  
  while(!queue.isEmpty())
  {
  
                 //element at head (Function in main graph class please use above link)
  ArrayList adjvertex=getNeighbours(queue.peek());
  System.out.println(queue.peek());
              //element removed at head
  queue.remove();
 
        if(adjvertex!=null)
  {
  for(int i=0;i<adjvertex.size();i++)
  {
               //element added at tail  
   queue.add((Character) adjvertex.get(i));
  }
  }
  }
  
  
 }

Comments

.

Popular posts from this blog

Adding Node at the End of Linked List

Adding Node at the End of Linked List:- The method takes two parameter one a head node of a linked list and other data too insert. public void addNodeEnd ( Node head , int data ) { if ( head == null ) { System . out . println ( "list is empty" ); return ; } Node node = new Node ( data ); Node temp = head ; while ( temp . next != null ) { temp = temp . next ; } temp . next = node ; } To Know the basic structure of the linked list click here

DEPTH FIRST SEARCH IN JAVA

DEPTH FIRST SEARCH IN JAVA public void dfs () { vertex [ 0 ]. visited = true ; displyVertex ( 0 ); stackobj . push ( 0 ); while (! stackobj . isEmpty ()) { int v = adjVertex (( Integer ) stackobj . peek ()); if ( v ==- 1 ) { stackobj . pop (); } else { vertex [ v ]. visited = true ; displyVertex ( v ); stackobj . push ( v ); } } }