Package problems.geeks.graph.Q002A_Depth_First_Traversal_for_a_Graph

Examples of problems.geeks.graph.Q002A_Depth_First_Traversal_for_a_Graph.GraphNode


    // use a queue to do breadth-first traversal
    Queue<GraphNode> queue = new LinkedList<GraphNode>();
    queue.add(node);
   
    while (!queue.isEmpty()) {
      GraphNode curr = queue.poll();
     
      if (!set.contains(curr)) {
        // visit the node
        visit(curr);
       
        // mark it as visited
        set.add(curr);
      }
     
      for (int i = 0; i < curr.neighbors.size(); i++) {
        GraphNode neighbor = curr.neighbors.get(i);
        if (!set.contains(neighbor)) {
          queue.add(neighbor);
        }
      }
    }
View Full Code Here


      }
    }
  }
 
  public static void main(String[] args) {
    GraphNode n0 = new GraphNode(0);
    GraphNode n1 = new GraphNode(1);
    GraphNode n2 = new GraphNode(2);
    GraphNode n3 = new GraphNode(3);
    GraphNode n4 = new GraphNode(4);
    GraphNode n5 = new GraphNode(5);
    GraphNode n6 = new GraphNode(6);
    GraphNode n7 = new GraphNode(7);
    GraphNode n8 = new GraphNode(8);
   
    n0.addNeighbors(new GraphNode[]{n1, n7});
    n1.addNeighbors(new GraphNode[]{n0, n2, n7});
    n2.addNeighbors(new GraphNode[]{n1, n3, n5, n8});
    n3.addNeighbors(new GraphNode[]{n2, n4, n5});
    n4.addNeighbors(new GraphNode[]{n3, n5});
    n5.addNeighbors(new GraphNode[]{n2, n3, n4, n6});
    n6.addNeighbors(new GraphNode[]{n5, n7, n8});
    n7.addNeighbors(new GraphNode[]{n0, n1, n6, n8});
    n8.addNeighbors(new GraphNode[]{n2, n6, n7});
   
    bfs(n0);
  }
View Full Code Here

TOP

Related Classes of problems.geeks.graph.Q002A_Depth_First_Traversal_for_a_Graph.GraphNode

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.