Beispiel #1
0
    // for performance comparison, compute connected components serially
    public Collection<Collection<Node<E>>> getCCSerially(UndirectedGraph<E> graph) {
      // node is one of the elements of nodes, nodes is a subset of dg's
      // nodes
      Queue<Node<E>> q = new LinkedList<Node<E>>();
      Collection<Node<E>> nodes = graph.getAllNodes();
      // hashmap to store the nodes, whose children have been visited
      HashMap<Node<E>, Integer> hashmap = new HashMap<Node<E>, Integer>(nodes.size());
      Iterator<Node<E>> itr = nodes.iterator();
      Collection<Node<E>> cc;
      Node<E> temp;
      Node<E> currentRoot;

      while (itr.hasNext()) {
        cc = new Vector<Node<E>>(INIT_SIZE_FOR_CC);
        currentRoot = itr.next();
        if (hashmap.get(currentRoot) != null) // the children already
          // been
          // visited
          continue;
        q.add(currentRoot);
        while (!q.isEmpty()) {
          temp = q.poll(); // temp' children definitely not visited
          cc.add(temp);
          hashmap.put(temp, 1); // temp's childrent been visited now
          Collection<AdjacentNode<E>> collection = graph.getLinkedNodes(temp);
          if (collection == null) continue;
          Iterator<AdjacentNode<E>> innerIter = collection.iterator();
          while (innerIter.hasNext()) {
            Node<E> toEnqueue = innerIter.next().getNode();
            if (hashmap.get(toEnqueue) == null) // toEnqueue's
              // children
              // not benn visited yet
              q.add(toEnqueue);
          }
        }
        if (cc.size() > 1) ccs.add(cc);
        else cc = null;
      }
      return ccs;
    }