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

How to build a project in eclipse with MAVEN build tool?

How to build a project in eclipse with MAVEN build tool? Step 1:- Install maven and set the path in my computer. Once path is set for java and maven you will get a screen With version installed in your system. Step 2:- Write a command mvn archetype:generate to build a project of your choice.This will give you a option to select a project from list. Step 3:- As soon as this operation will complete maven give you choice to choose project.Search for maven-archetype-webapp this will build a web project with basic structure. Step4:- Follow the below procedure to give name , version ,package ,artifact and group id of your choice. Step 5:- You will get screen with build success.Congrats your project is build in directory. Step 6: Go in the directory to check for the folders automatically created by maven. You will get pom file and src folder and the package folder. Step:-7  Move to the directry having pom.xml and run mvn ecl

Delete node at a given position in Linked List

Delete node at a given position in Linked List //delete node by position in linked list public Node deleteKeyAtPosition ( Node head , int position ) { Node temp = head ; Node prevtemp = temp ; int c = 1 ; //if position is head if ( position == 1 ) { head = head . next ; return head ; } //position +1 because we have to go till that point while ( c != position + 1 ) { if ( c == position && position != 1 ) { prevtemp . next = temp . next ; temp . next = null ; temp = prevtemp ; } prevtemp = temp ; temp = temp . next ; c ++; } return head ; }