Pages

Tuesday 24 May 2016

Depth-first search (DFS) in Java

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.

The non-recursive implementation is similar to breadth-first search but differs from it in two ways: it uses a stack instead of a queue, and it delays checking whether a vertex has been discovered until the vertex is popped from the stack rather than making this check before pushing the vertex.

Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered

A recursive implementation of DFS: 
procedure DFS(G,v):
    label v as discovered
    for all edges from v to w in G.adjacentEdges(v) do
        if vertex w is not labeled as discovered then
            recursively call DFS(G,w)

A non-recursive implementation of DFS:       
procedure DFS-iterative(G,v):
    let S be a stack
    S.push(v)
    while S is not empty
          v = S.pop()
          if v is not labeled as discovered:
              label v as discovered
              for all edges from v to w in G.adjacentEdges(v) do
                  S.push(w)


Non recursive implementation of DFS:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

public class GraphDFS {

   // No. of vertices
   private intvertives;
   //Adjacency Lists - Edges
   privateLinkedList<Integer> adj[];

   GraphDFS(int vertices) {
      vertives = vertices;
      adj = newLinkedList[vertices];
      for (inti=0; i<vertices; ++i) {
         adj[i] = newLinkedList<Integer>();
      }
   }

   void addEdge(intv,int w) {
      adj[v].add(w);
   }

   private voidtraverseDFS(int node) {
      /** Mark true if vertices are visited. */
      boolean visited[] = newboolean[vertives];

      /** Create a queue for DFS */
      Stack<Integer> stack = newStack<Integer>();

      /** mark start node as visited by default. */
      visited[node] = true;
      stack.add(node);

      while(!stack.isEmpty()) {

         /** poll the first element of queue. */
         node = stack.pop();

         System.out.print(node+" ");

         /** add all the nearest node of processing node. */
         Iterator<Integer> iter = adj[node].listIterator();
         while (iter.hasNext()) {
            int next = iter.next();
            if (!visited[next]) {
               visited[next] = true;
               stack.push(next);
            }
         }
      }
   }

   public static void main(String args[]) {

      /** Create a graph of size . */
      GraphDFS graph = newGraphDFS(4);

      /** Add edges in the graph.*/
      graph.addEdge(0, 1);
      graph.addEdge(0, 2);
      graph.addEdge(1, 2);
      graph.addEdge(2, 0);
      graph.addEdge(2, 3);
      graph.addEdge(3, 2);
      graph.addEdge(3, 1);

      System.out.println("DFS Traversal : ");

      /** start BS from any given node.*/
      graph.traverseDFS(1);
   }
}
Output:
DFS Traversal :
1 2 3 0

Breadth-first search (BFS) Implemetation in Java

Breadth-first seach implementation in java 


import java.util.Iterator;
import java.util.LinkedList;

public class GraphBFS {

     // No. of vertices
     private intvertives;

     //Adjacency Lists - Edges
     private LinkedList<Integer> adj[];

     GraphBFS(int vertices) {
           vertives = vertices;
           adj = newLinkedList[vertices];
           for (inti=0; i<vertices; ++i) {
                adj[i] = new LinkedList<Integer>();
           }
     }

     void addEdge(intv,int w) {
           adj[v].add(w);
     }

     private voidtraverseBFS(int node) {
           /** Mark true if vertices are visited. */
           boolean visited[] = newboolean[vertives];

           /** Create a queue for BFS */
           LinkedList<Integer> queue = newLinkedList<Integer>();

           /** mark start node as visited by default. */
           visited[node] = true;
           queue.add(node);

           while(!queue.isEmpty()) {

                /** poll the first element of queue. */
                node = queue.poll();

                System.out.print(node+" ");

                /** add all the nearest node of processing node. */
                Iterator<Integer> iter = adj[node].listIterator();
                while (iter.hasNext()) {
                     intnext = iter.next();
                     if(!visited[next]) {
                           visited[next] = true;
                           queue.add(next);
                     }
                }
           }
     }

     public static void main(String args[]) {

           /** Create a graph of size . */
           GraphBFS graph = newGraphBFS(4);

           /** Add edges in the graph.*/
           graph.addEdge(0, 1);
           graph.addEdge(0, 2);
           graph.addEdge(1, 2);
           graph.addEdge(2, 0);
           graph.addEdge(2, 3);
           graph.addEdge(3, 2);
           graph.addEdge(3, 1);

           System.out.println("BFS Traversal : ");

           /** start BS from any given node.*/
           graph.traverseBFS(1);
     }
}
Output
BFS Traversal:
1 2 0 3

Monday 23 May 2016

Breadth-first search (BFS)

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a ‘search key’) and explores the neighbor nodes first, before moving to the next level neighbors.



Pseudocode

Input: A graph G and a starting vertex v of G
Output: All vertices reachable from v labeled as explored.

A non-recursive implementation of breadth-first search:


Breadth-First-Search(G, v):
    for each node n in G:           
        n.distance = INFINITY       
        n.parent = NIL

    create empty queue Q     

    v.distance = 0
    Q.enqueue(v)                     

    while Q is not empty:       
    
        u = Q.dequeue()
    
        for each node n that is adjacent to u:
            if n.distance == INFINITY:
                n.distance = u.distance + 1
                n.parent = u
                Q.enqueue(n)