Friday 4 October 2013

Depth First Search


     /*
          TIME COMPLEXITY :
          O(|v| + |E|).
          
          APPLICATIONS OF DFS
          Finding strongly connected components in a graph (Kosaraju Algorithm).
          Topological Sorting.
          Solving Maze.
     */
     
     public void recursiveDFS(Vertex sourceVertex,boolean visited[]) {
          //Process the top vertex from stack and put it to explored set of vertices.
          visited[sourceVertex.vertexId] = true;
          System.out.println(sourceVertex.vertexId);
          
          for(int i=0; i<sourceVertex.edges.size(); i++) {
               //Push all not visited vertices reachable from process vertex 
               //one by one and aggressively search to deeper levels.
               //backtrack when no more path can be taken and 
               //process all other vertices reachable from processed vertex
               Vertex target = sourceVertex.edges.get(i).Target;
               if(!visited[target.vertexId]) {
                    recursiveDFS(target,visited);
               }
          }
     }

     public void DFS(int sourceVertex) {
          System.out.println("DFS Traversal");
          int i;
          
          //Initially put all vertices in unexplored set.
          boolean visited[] = new boolean[totalVertices];
          for(i=0; i<totalVertices; i++)
               visited[i] = false;
          
          //Push source vertex in stack.
          recursiveDFS(vertices[sourceVertex],visited);
     }


No comments:

Post a Comment