Skip to main content

Depth-first search

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.
A version of depth-first search was investigated in the 19th century by French mathematician Charles Pierre Trémaux as a strategy for solving mazes.

The Program For DFS is Given Below:

////////////////////////////////////////////////////////////////
class StackX
   {
   private final int SIZE = 20;
   private int[] st;
   private int top;
// ------------------------------------------------------------
   public StackX()           // constructor
      {
      st = new int[SIZE];    // make array
      top = -1;
      }
// ------------------------------------------------------------
   public void push(int j)   // put item on stack
      { st[++top] = j; }
// ------------------------------------------------------------
   public int pop()          // take item off stack
      { return st[top--]; }
// ------------------------------------------------------------
   public int peek()         // peek at top of stack
      { return st[top]; }
// ------------------------------------------------------------
   public boolean isEmpty()  // true if nothing on stack
      { return (top == -1); }
// ------------------------------------------------------------
   }  // end class StackX
////////////////////////////////////////////////////////////////
class Vertex
   {
   public char label;        // label (e.g. 'A')
   public boolean wasVisited;
// ------------------------------------------------------------
   public Vertex(char lab)   // constructor
      {
      label = lab;
      wasVisited = false;
      }
// ------------------------------------------------------------
   }  // end class Vertex
////////////////////////////////////////////////////////////////
class Graph
   {
   private final int MAX_VERTS = 20;
   private Vertex vertexList[]; // list of vertices
   private int adjMat[][];      // adjacency matrix
   private int nVerts;          // current number of vertices
   private StackX theStack;
// ------------------------------------------------------------
   public Graph()               // constructor
      {
      vertexList = new Vertex[MAX_VERTS];
                                          // adjacency matrix
      adjMat = new int[MAX_VERTS][MAX_VERTS];
      nVerts = 0;
      for(int y=0; y<MAX_VERTS; y++)      // set adjacency
         for(int x=0; x<MAX_VERTS; x++)   //    matrix to 0
            adjMat[x][y] = 0;
      theStack = new StackX();
      }  // end constructor
// ------------------------------------------------------------
   public void addVertex(char lab)
      {
      vertexList[nVerts++] = new Vertex(lab);
      }
// ------------------------------------------------------------
   public void addEdge(int start, int end)
      {
      adjMat[start][end] = 1;
      adjMat[end][start] = 1;
      }
// ------------------------------------------------------------
   public void displayVertex(int v)
      {
      System.out.print(vertexList[v].label);
      }
// ------------------------------------------------------------
   public void dfs()  // depth-first search
      {                                 // begin at vertex 0
      vertexList[0].wasVisited = true;  // mark it
      displayVertex(0);                 // display it
      theStack.push(0);                 // push it

      while( !theStack.isEmpty() )      // until stack empty,
         {
         // get an unvisited vertex adjacent to stack top
         int v = getAdjUnvisitedVertex( theStack.peek() );
         if(v == -1)                    // if no such vertex,
            theStack.pop();
         else                           // if it exists,
            {
            vertexList[v].wasVisited = true;  // mark it
            displayVertex(v);                 // display it
            theStack.push(v);                 // push it
            }
         }  // end while

      // stack is empty, so we're done
      for(int j=0; j<nVerts; j++)          // reset flags
         vertexList[j].wasVisited = false;
      }  // end dfs
// ------------------------------------------------------------
   // returns an unvisited vertex adj to v
   public int getAdjUnvisitedVertex(int v)
      {
      for(int j=0; j<nVerts; j++)
         if(adjMat[v][j]==1 && vertexList[j].wasVisited==false)
            return j;
      return -1;
      }  // end getAdjUnvisitedVertex()
// ------------------------------------------------------------
   }  // end class Graph
////////////////////////////////////////////////////////////////
class DFSApp
   {
   public static void main(String[] args)
      {
      Graph theGraph = new Graph();
      theGraph.addVertex('A');    // 0  (start for dfs)
      theGraph.addVertex('B');    // 1
      theGraph.addVertex('C');    // 2
      theGraph.addVertex('D');    // 3
      theGraph.addVertex('E');    // 4

      theGraph.addEdge(0, 1);     // AB
      theGraph.addEdge(1, 2);     // BC
      theGraph.addEdge(0, 3);     // AD
      theGraph.addEdge(3, 4);     // DE

      System.out.print("Visits: ");
      theGraph.dfs();             // depth-first search
      System.out.println();
      }  // end main()
   }  // end class DFSApp
////////////////////////////////////////////////////////////////

Comments

Popular posts from this blog

Login and Registration Example in JSP with Session

Those who want to start with jsp and MySQL, this is an excellent example for themselves. Here you can learn how to insert data to MySQL using JSP. Also you can learn about session handling in jsp. 1 2 3 4 5 6 7 8 9 10 CREATE TABLE `members` (    `id` int (10) unsigned NOT NULL auto_increment,    `first_name` varchar (45) NOT NULL ,    `last_name` varchar (45) NOT NULL ,    `email` varchar (45) NOT NULL ,    `uname` varchar (45) NOT NULL ,    `pass` varchar (45) NOT NULL ,    `regdate` date NOT NULL ,    PRIMARY KEY   (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; index.jsp 1 2 3 4 5 6 ...

Timer funcitons in JavaScript: Reminder Script

Timers are used in web pages and we will discuss how to setup one and how to use one with an example. The function setTimeout() in function is used and here is its general syntax. mytime = setTimeout(expression, msec); mytime  is the identifier used to identify the current timeout function.  expression  is the statement that is to be executed after the specified time has ticked off.  msec  is the duration of time in milliseconds after which the expression will be executed.  You can see by using setTimeout function we can execute any function or object after a set of time. For example if msec is set 5000 then the expression will be executed after 5 seconds or 5000 milliseconds.  We will try one example where we will have four period buttons and each button will set a different time for another function to execute and display a alert button. We will call it as a reminder script and we will get one alert box based on the period button we click...

Binary Addition

/* File Name : BinAdd.java */    import java.util.*; public class BinAdd    {  public static String addBit(String a, String b, String c)  { String r=""; if(a.equals("1") && b.equals("0") || a.equals("0") && b.equals("1")) { if( c.equals("0")) r="1"; else { r="0"; c="1"; } } else if( a.equals("0") && b.equals("0") ) { if(c.equals("0")) r="0"; else r="1"; } else if( a.equals("1") && b.equals("1") ) { if(c.equals("0")){ r="0"; c="1"; } else { r="1"; c="1"; } } return c+r; }   public static String add(String a, String b)   { String r=""; int len=a.length(); String carry="0"; for(int i=len-1;i...

Real time changing Clock showing date and time

We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.  We have seen in our  date object example how to display current date and time   where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using  setTimeout function . This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.  Here is the demo of this script and code is given below that.  Sat Apr 23 2016 08:27:22 GMT+0530 (IST)   Here is the code <html> <head> <title>(Type a title for your page here)</title> <script type="text/javascript...