Skip to main content

Depth First Search Implementation in Graph

Depth First Search Implementation in Graph



--Graph

//This is a class to define the vertex in a graph

public class Vertex {

  char label;
  boolean visited;
  
   public Vertex(char label){
    this.label=label;
    this.visited=false;
   }

package Graph;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


// this class is abstract because we won't allow you make instance of it , it is of no use until not extended
abstract public class GraphBase {
 
 //declaring instance of vertex
 Vertex vertex;
 //declaring an array of vertex to hold all the vertex
 static Vertex[] vertexlist=new Vertex[10];
 //declaring edgelist to hold all edges key is vertex value is neighbouring vertex
 static HashMap<Character,ArrayList<Character>> edgelist=new HashMap<>();
 //count of vertex and edge
 static int vertexcount=0;
 int edgecount=0;
 
 /*
  * This function takes a label and insert in the vertex list as well as edge list since it is new vertex it will add
  * null to its adjoining vertices
  */
 int addVertex(char label)
 {
  vertex=new Vertex(label);
  vertexlist[vertexcount]=vertex;
  System.out.println(vertexlist[vertexcount].label);
  edgelist.put(vertex.label, null);
  vertexcount++;
  return vertexcount;
 }

 /*
  * in the same edgelist we add the vertices that are now in connection by simply updating value for a key
  */
 int addEdge(char v1,char[] v2)
 {
  ArrayList<Character> vertextoadd=new ArrayList<>();
  for(int i=0;i<v2.length;i++)
  {
   edgecount++;
  vertextoadd.add(v2[i]);
  }
  edgelist.put(v1, vertextoadd);
  
  
  return edgecount;
 }
 
 //A function that returns neighbour vertices for a given vertex
 
 ArrayList getNeighbours(char vertex)
 {
  return edgelist.get(vertex);
 }
 
 
 void listOfVertex()
 {
  System.out.println("Total Vertex:"+ vertexcount);
  
  //This is how we traverse over a hashmap
  for(Object key:edgelist.keySet())
  {
   System.out.println(key+" " +edgelist.get(key));
  }
  
 }
}

package Graph;

import java.util.ArrayList;
import java.util.Stack;

public class GraphSearch extends GraphBase {
 
 /*Depth First Search 
  * Basically it works on the concept of stack we take vertex from it serach its neighbour and do the same till no vertex left
 *
 *1. Push first element in stack
 *2. Search for its neigbour and add them in stack and pop the vertex
 *3. do same for rest of the vertices until there is no vertex left in a stack
 *
 */
 void searchDFS()
 { 
 Stack<Character> stack=new Stack<>();
 
 stack.push(vertexlist[0].label);
 
 while(!stack.isEmpty())
 {
  System.out.println("traverse"+stack.peek());
  ArrayList adjvertex=getNeighbours(stack.peek());
  stack.pop();
  if(adjvertex!=null)
  {
  for(int i=adjvertex.size()-1;i>=0;i--)
  {
   stack.push((Character) adjvertex.get(i));
  }
  }
 }
 
 
 
 }

}

package Graph;

import java.util.Map.Entry;

public class GraphImpl extends GraphBase {

 public static void main(String[] args)
 {
  GraphImpl graph=new GraphImpl();
  //Adding vertices
  graph.addVertex('A');
  graph.addVertex('B');
  graph.addVertex('C');
  graph.addVertex('D');
  graph.addVertex('E');
  graph.addVertex('F');
  graph.addVertex('G');
  graph.addVertex('H');
  
  //Adding edges and this is how we initialize inline array
  graph.addEdge('A', new char[]{'B','C'});
  graph.addEdge('B', new char[]{'D','E'});
  graph.addEdge('C',new char[]{'F','G'} );
  graph.addEdge('D',new char[]{'H'} );
  graph.listOfVertex();
  
  GraphSearch search=new GraphSearch();
  search.searchDFS();
 }
}



For BFS implementation please use below link:-

breadth-first-search-implementation-in-java

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 ); } } }