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

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

Introduction

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

Prototype

@Override
Set<N> predecessors(Object node);

Source Link

Document

Returns all nodes in this graph adjacent to node which can be reached by traversing node 's #inEdges(Object) incoming edges against the direction (if any) of the edge.

Usage

From source file:edu.uci.ics.jung.graph.util.TreeUtils.java

/**
 * A graph is "forest-shaped" if it is directed, acyclic, and each node has at most one
 * predecessor./*from   www .ja  v a2 s.co m*/
 */
public static <N> boolean isForestShaped(Network<N, ?> graph) {
    checkNotNull(graph, "graph");
    return graph.isDirected() && !Graphs.hasCycle(graph)
            && graph.nodes().stream().allMatch(node -> graph.predecessors(node).size() <= 1);
}

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);//from w w w .  j  av a2  s.  c om

    // 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;
}