Friday 4 October 2013

Breadth First Search in a Graph.



     /* 
        ALGORITHM
        Enqueue the root node
        Dequeue a node and examine it
           If the element sought is found in this node, quit the search and return a result.
           Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
        If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
        If the queue is not empty, repeat from Step 2.
 
 COMPLEXITY
        BFS is very first and runs in linear time O(|V| + |E|) since each vertex and edge is explored once in worst case.
        
        APPLICATIONS
        Finding shortest path between 2 nodes in an undirected graph.
        Checking if a graph is bipartite
        Ford Fulkerson method for computing maximum flow in a network.
        Serialization/Deserialization of a binary tree.
        Finding all nodes within one connected components.
       
     */
     
     public void BFS(int sourceVertex) {
          System.out.println("BFS Traversal");
          int i,targetId;
          ArrayList<Vertex> queue = new ArrayList<>();
          boolean visited[] = new boolean[totalVertices];
          
          //Put all the vertices to unexplored set of vertices, initially.
          for(i=0; i<totalVertices; i++) 
               visited[i] = false;
          
          //Put source vertex to explored vertices set.
          visited[sourceVertex] = true;
          queue.add(vertices[sourceVertex]);
          while(!queue.isEmpty()) {
               
               //Remove the very first vertex from the queue.
               Vertex vertex = queue.get(0);
               queue.remove(0);
               
               //Process the removed vertex.
               System.out.println(vertex.vertexId);
               
               for(i=0; i<vertex.edges.size(); i++) {
                    
                    //Get all the vertices reachable from processed vertex and add them to queue.
                    //put the processed vertex to explored set of vertices, so that its not explored again.
                    targetId = vertex.edges.get(i).Target.vertexId;
                    if(!visited[targetId]) {
                         queue.add(vertex.edges.get(i).Target);
                         visited[targetId] = true;
                    }
               }
          }
     }



No comments:

Post a Comment