示例#1
0
  public static List findCycles(DigraphIteration graph) {
    ArrayStack stack = new ArrayStack();
    ArrayStack path = new ArrayStack();
    Set seen = new HashSet();
    List cycles = new ArrayList();
    Iterator vertexIterator = graph.vertexIterator();

    while (vertexIterator.hasNext()) {
      while (vertexIterator.hasNext()) {
        Object vertex = vertexIterator.next();
        if (seen.add(vertex)) {
          stack.push(graph.outgoingIterator(vertex));
          path.push(vertex);
          break;
        }
      }

      while (!stack.isEmpty()) {
        ArcIterator i = (ArcIterator) stack.peek();
        Object origin = i.getOrigin();
        boolean subtreeIsTraversed = true;
        while (i.hasNext()) {
          i.next();
          Object dst = i.getDestination();
          int index = path.indexOf(dst);
          if (index < 0) {
            seen.add(dst);
            stack.push(graph.outgoingIterator(dst));
            path.push(dst);
            subtreeIsTraversed = false;
            break;
          } else {
            cycles.add(new ArrayList(path.subList(index, path.size())));
          }
        }
        if (subtreeIsTraversed) {
          stack.pop();
          path.pop();
        }
      }
    }
    return cycles;
  }
示例#2
0
 public static Digraph randomizeTree(
     Digraph digraph, int maxChildren, int maxLevels, Random randomizer) {
   int vertexIndex = 1;
   Object root = new Integer(vertexIndex);
   List level = Collections.singletonList(root);
   digraph.addVertex(root);
   for (int i = 1; i < maxLevels; i++) {
     List childLevel = new ArrayList(level.size() * maxChildren);
     for (Iterator j = level.iterator(); j.hasNext(); ) {
       Object parent = j.next();
       int childCount = randomizer.nextInt(maxChildren + 1);
       for (int k = 0; k < childCount; k++) {
         Object child = new Integer(++vertexIndex);
         digraph.addVertex(child);
         digraph.putArc(parent, child, Boolean.TRUE);
         childLevel.add(child);
       }
     }
     if (childLevel.isEmpty()) break;
     level = childLevel;
   }
   return digraph;
 }