Example usage for com.google.common.graph Network allowsSelfLoops

List of usage examples for com.google.common.graph Network allowsSelfLoops

Introduction

In this page you can find the example usage for com.google.common.graph Network allowsSelfLoops.

Prototype

boolean allowsSelfLoops();

Source Link

Document

Returns true if this graph allows self-loops (edges that connect a node to itself).

Usage

From source file:org.apache.beam.runners.dataflow.worker.graph.Networks.java

/** Returns a set of nodes sorted in topological order. */
public static <N, E> Set<N> topologicalOrder(Network<N, E> network) {
    // TODO: Upgrade Guava and remove this method if topological sorting becomes
    // supported externally or remove this comment if its not going to be supported externally.

    checkArgument(network.isDirected(), "Only directed networks are supported, given %s", network);
    checkArgument(!network.allowsSelfLoops(), "Only networks without self loops are supported, given %s",
            network);//  w  ww  . j a  v a2  s  .  com

    // Linked hashset will prevent duplicates from appearing and will maintain insertion order.
    LinkedHashSet<N> nodes = new LinkedHashSet<>(network.nodes().size());
    Queue<N> processingOrder = new ArrayDeque<>();
    // Add all the roots
    for (N node : network.nodes()) {
        if (network.inDegree(node) == 0) {
            processingOrder.add(node);
        }
    }

    while (!processingOrder.isEmpty()) {
        N current = processingOrder.remove();
        // If all predecessors have already been added, then we can add this node, otherwise
        // we need to add the node to the back of the processing queue.
        if (nodes.containsAll(network.predecessors(current))) {
            nodes.add(current);
            processingOrder.addAll(network.successors(current));
        } else {
            processingOrder.add(current);
        }
    }

    return nodes;
}