001/*
002 * Copyright (C) 2014 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.graph;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.collect.Iterators.transform;
022import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
023import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH;
024import static com.google.common.graph.Graphs.TransitiveClosureSelfLoopStrategy.ADD_SELF_LOOPS_ALWAYS;
025import static java.util.Objects.requireNonNull;
026
027import com.google.common.collect.ImmutableSet;
028import com.google.errorprone.annotations.CanIgnoreReturnValue;
029import java.util.ArrayDeque;
030import java.util.Collection;
031import java.util.Deque;
032import java.util.Iterator;
033import java.util.Map;
034import java.util.Objects;
035import java.util.Optional;
036import java.util.Set;
037import org.jspecify.annotations.Nullable;
038
039/**
040 * Static utility methods for {@link Graph}, {@link ValueGraph}, and {@link Network} instances.
041 *
042 * @author James Sexton
043 * @author Joshua O'Madadhain
044 * @since 20.0
045 */
046public final class Graphs extends GraphsBridgeMethods {
047
048  private Graphs() {}
049
050  // Graph query methods
051
052  /**
053   * Returns true if {@code graph} has at least one cycle. A cycle is defined as a non-empty subset
054   * of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) starting
055   * and ending with the same node.
056   *
057   * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
058   */
059  public static <N> boolean hasCycle(Graph<N> graph) {
060    int numEdges = graph.edges().size();
061    if (numEdges == 0) {
062      return false; // An edge-free graph is acyclic by definition.
063    }
064    if (!graph.isDirected() && numEdges >= graph.nodes().size()) {
065      return true; // Optimization for the undirected case: at least one cycle must exist.
066    }
067
068    Map<Object, NodeVisitState> visitedNodes = newHashMapWithExpectedSize(graph.nodes().size());
069    for (N node : graph.nodes()) {
070      if (subgraphHasCycle(graph, visitedNodes, node)) {
071        return true;
072      }
073    }
074    return false;
075  }
076
077  /**
078   * Returns true if {@code network} has at least one cycle. A cycle is defined as a non-empty
079   * subset of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges)
080   * starting and ending with the same node.
081   *
082   * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1).
083   */
084  public static boolean hasCycle(Network<?, ?> network) {
085    // In a directed graph, parallel edges cannot introduce a cycle in an acyclic graph.
086    // However, in an undirected graph, any parallel edge induces a cycle in the graph.
087    if (!network.isDirected()
088        && network.allowsParallelEdges()
089        && network.edges().size() > network.asGraph().edges().size()) {
090      return true;
091    }
092    return hasCycle(network.asGraph());
093  }
094
095  /**
096   * Performs a traversal of the nodes reachable from {@code startNode}. If we ever reach a node
097   * we've already visited (following only outgoing edges and without reusing edges), we know
098   * there's a cycle in the graph.
099   */
100  private static <N> boolean subgraphHasCycle(
101      Graph<N> graph, Map<Object, NodeVisitState> visitedNodes, N startNode) {
102    Deque<NodeAndRemainingSuccessors<N>> stack = new ArrayDeque<>();
103    stack.addLast(new NodeAndRemainingSuccessors<>(startNode));
104
105    while (!stack.isEmpty()) {
106      // To peek at the top two items, we need to temporarily remove one.
107      NodeAndRemainingSuccessors<N> top = stack.removeLast();
108      NodeAndRemainingSuccessors<N> prev = stack.peekLast();
109      stack.addLast(top);
110
111      N node = top.node;
112      N previousNode = prev == null ? null : prev.node;
113      if (top.remainingSuccessors == null) {
114        NodeVisitState state = visitedNodes.get(node);
115        if (state == NodeVisitState.COMPLETE) {
116          stack.removeLast();
117          continue;
118        }
119        if (state == NodeVisitState.PENDING) {
120          return true;
121        }
122
123        visitedNodes.put(node, NodeVisitState.PENDING);
124        top.remainingSuccessors = graph.successors(node).iterator();
125      }
126
127      if (top.remainingSuccessors.hasNext()) {
128        N nextNode = top.remainingSuccessors.next();
129        if (canTraverseWithoutReusingEdge(graph, nextNode, previousNode)) {
130          stack.addLast(new NodeAndRemainingSuccessors<>(nextNode));
131        }
132        continue;
133      }
134
135      stack.removeLast();
136      visitedNodes.put(node, NodeVisitState.COMPLETE);
137    }
138    return false;
139  }
140
141  private static final class NodeAndRemainingSuccessors<N> {
142    final N node;
143
144    /**
145     * The successors left to be visited, or {@code null} if we just added this {@code
146     * NodeAndRemainingSuccessors} instance to the stack. In the latter case, we'll compute the
147     * successors if we determine that we need them after we've performed the initial processing of
148     * the node.
149     */
150    @Nullable Iterator<N> remainingSuccessors;
151
152    NodeAndRemainingSuccessors(N node) {
153      this.node = node;
154    }
155  }
156
157  /**
158   * Determines whether an edge has already been used during traversal. In the directed case a cycle
159   * is always detected before reusing an edge, so no special logic is required. In the undirected
160   * case, we must take care not to "backtrack" over an edge (i.e. going from A to B and then going
161   * from B to A).
162   */
163  private static boolean canTraverseWithoutReusingEdge(
164      Graph<?> graph, Object nextNode, @Nullable Object previousNode) {
165    if (graph.isDirected() || !Objects.equals(previousNode, nextNode)) {
166      return true;
167    }
168    // This falls into the undirected A->B->A case. The Graph interface does not support parallel
169    // edges, so this traversal would require reusing the undirected AB edge.
170    return false;
171  }
172
173  /**
174   * Returns the transitive closure of {@code graph}. The transitive closure of a graph {@code G} is
175   * a graph {@code T} that is a supergraph of {@code G}, augmented by, for each pair of nodes A and
176   * B, an edge connecting node A to node B if there is a sequence of edges in {@code G} starting at
177   * A and ending at B.
178   *
179   * <p>{@code strategy} defines the circumstances under which self-loops will be added to the
180   * transitive closure graph.
181   *
182   * <p>This is a "snapshot" based on the current topology of {@code graph}, rather than a live view
183   * of the transitive closure of {@code graph}. In other words, the returned {@link Graph} will not
184   * be updated after modifications to {@code graph}.
185   *
186   * @since 33.6.0
187   */
188  // TODO(b/31438252): Consider optimizing for undirected graphs.
189  public static <N> ImmutableGraph<N> transitiveClosure(
190      Graph<N> graph, TransitiveClosureSelfLoopStrategy strategy) {
191    ImmutableGraph.Builder<N> transitiveClosure =
192        GraphBuilder.from(graph).allowsSelfLoops(true).immutable();
193
194    for (N node : graph.nodes()) {
195      // add each node explicitly to include isolated nodes
196      transitiveClosure.addNode(node);
197      for (N reachableNode : getReachableNodes(graph, node, strategy)) {
198        transitiveClosure.putEdge(node, reachableNode);
199      }
200    }
201    return transitiveClosure.build();
202  }
203
204  /**
205   * Equivalent to {@code transitiveClosure(graph, ADD_SELF_LOOPS_ALWAYS)}. Callers should look at
206   * the different strategy options that the new method supports rather than simply migrating to the
207   * new method with the existing behavior; we believe that most callers will want to use the {@code
208   * ADD_SELF_LOOPS_FOR_CYCLES} strategy.
209   *
210   * @since 33.1.0 (present with return type {@code Graph} since 20.0)
211   * @deprecated Use {@link #transitiveClosure(Graph, TransitiveClosureSelfLoopStrategy)} instead.
212   */
213  @SuppressWarnings("InlineMeSuggester") // We expect most users to want to change behavior.
214  @Deprecated
215  public static <N> ImmutableGraph<N> transitiveClosure(Graph<N> graph) {
216    return transitiveClosure(graph, ADD_SELF_LOOPS_ALWAYS);
217  }
218
219  /**
220   * Returns the nodes reachable from {@code node} in {@code graph}, according to the given {@code
221   * strategy}.
222   */
223  private static <N> Iterable<N> getReachableNodes(
224      Graph<N> graph, N node, TransitiveClosureSelfLoopStrategy strategy) {
225    Traverser<N> traverser = Traverser.forGraph(graph);
226    switch (strategy) {
227      case ADD_SELF_LOOPS_ALWAYS: // always include 'node'
228        return traverser.breadthFirst(node);
229      case ADD_SELF_LOOPS_FOR_CYCLES: // include 'node' if and only if there's an incident cycle
230        // note that if 'node' has a self-loop, it will appear in its successors
231        return traverser.breadthFirst(graph.successors(node));
232    }
233    throw new IllegalArgumentException("Unrecognized strategy: " + strategy);
234  }
235
236  /**
237   * A strategy for adding self-loops to {@linkplain #transitiveClosure(Graph,
238   * TransitiveClosureSelfLoopStrategy) the transitive closure graph}. All strategies preserve
239   * self-loops that are present in the original graph.
240   *
241   * <p>The strategies differ based on how they define "cycle incident to a node".
242   *
243   * @since 33.6.0
244   */
245  public enum TransitiveClosureSelfLoopStrategy {
246    /**
247     * Add a self-loop to each node in the original graph; this is based on a definition of "cycle
248     * incident to a node" that includes zero-length cycles. This matches the behavior of the
249     * now-deprecated {@link #transitiveClosure(Graph)} method.
250     */
251    ADD_SELF_LOOPS_ALWAYS,
252    /**
253     * Add a self-loop to each node that is incident to a cycle of length one or greater in the
254     * original graph.
255     */
256    ADD_SELF_LOOPS_FOR_CYCLES
257  }
258
259  /**
260   * Returns the set of nodes that are reachable from {@code node}. Specifically, it returns all
261   * nodes {@code v} such that there exists a path (a sequence of adjacent outgoing edges) starting
262   * at {@code node} and ending at {@code v}. This implementation includes {@code node} as the first
263   * element in the result.
264   *
265   * <p>If needed, the {@link Traverser} class provides more flexible and lighter-weight ways to
266   * list the nodes reachable from a given node or nodes. See the <a
267   * href="https://github.com/google/guava/wiki/GraphsExplained#Graph-traversal">"Graph traversal"
268   * section of the Guava User's Guide</a> for more information.
269   *
270   * <p>The {@link Set} returned is a "snapshot" based on the current topology of {@code graph},
271   * rather than a live view. In other words, modifications to {@code graph} made after this method
272   * returns will not be reflected in the set.
273   *
274   * @throws IllegalArgumentException if {@code node} is not present in {@code graph}
275   * @since 33.1.0 (present with return type {@code Set} since 20.0)
276   */
277  public static <N> ImmutableSet<N> reachableNodes(Graph<N> graph, N node) {
278    checkNotNull(node);
279    checkArgument(graph.nodes().contains(node), NODE_NOT_IN_GRAPH, node);
280    return ImmutableSet.copyOf(Traverser.forGraph(graph).breadthFirst(node));
281  }
282
283  // Graph mutation methods
284
285  // Graph view methods
286
287  /**
288   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
289   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
290   */
291  public static <N> Graph<N> transpose(Graph<N> graph) {
292    if (!graph.isDirected()) {
293      return graph; // the transpose of an undirected graph is an identical graph
294    }
295
296    if (graph instanceof TransposedGraph) {
297      return ((TransposedGraph<N>) graph).graph;
298    }
299
300    return new TransposedGraph<>(graph);
301  }
302
303  /**
304   * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other
305   * properties remain intact, and further updates to {@code graph} will be reflected in the view.
306   */
307  public static <N, V> ValueGraph<N, V> transpose(ValueGraph<N, V> graph) {
308    if (!graph.isDirected()) {
309      return graph; // the transpose of an undirected graph is an identical graph
310    }
311
312    if (graph instanceof TransposedValueGraph) {
313      return ((TransposedValueGraph<N, V>) graph).graph;
314    }
315
316    return new TransposedValueGraph<>(graph);
317  }
318
319  /**
320   * Returns a view of {@code network} with the direction (if any) of every edge reversed. All other
321   * properties remain intact, and further updates to {@code network} will be reflected in the view.
322   */
323  public static <N, E> Network<N, E> transpose(Network<N, E> network) {
324    if (!network.isDirected()) {
325      return network; // the transpose of an undirected network is an identical network
326    }
327
328    if (network instanceof TransposedNetwork) {
329      return ((TransposedNetwork<N, E>) network).network;
330    }
331
332    return new TransposedNetwork<>(network);
333  }
334
335  static <N> EndpointPair<N> transpose(EndpointPair<N> endpoints) {
336    if (endpoints.isOrdered()) {
337      return EndpointPair.ordered(endpoints.target(), endpoints.source());
338    }
339    return endpoints;
340  }
341
342  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
343  // AbstractGraph) derives its behavior from calling successors().
344  private static final class TransposedGraph<N> extends ForwardingGraph<N> {
345    private final Graph<N> graph;
346
347    TransposedGraph(Graph<N> graph) {
348      this.graph = graph;
349    }
350
351    @Override
352    Graph<N> delegate() {
353      return graph;
354    }
355
356    @Override
357    public Set<N> predecessors(N node) {
358      return delegate().successors(node); // transpose
359    }
360
361    @Override
362    public Set<N> successors(N node) {
363      return delegate().predecessors(node); // transpose
364    }
365
366    @Override
367    public Set<EndpointPair<N>> incidentEdges(N node) {
368      return new IncidentEdgeSet<N>(this, node, IncidentEdgeSet.EdgeType.BOTH) {
369        @Override
370        public Iterator<EndpointPair<N>> iterator() {
371          return transform(
372              delegate().incidentEdges(node).iterator(),
373              edge -> EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU()));
374        }
375      };
376    }
377
378    @Override
379    public int inDegree(N node) {
380      return delegate().outDegree(node); // transpose
381    }
382
383    @Override
384    public int outDegree(N node) {
385      return delegate().inDegree(node); // transpose
386    }
387
388    @Override
389    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
390      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
391    }
392
393    @Override
394    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
395      return delegate().hasEdgeConnecting(transpose(endpoints));
396    }
397  }
398
399  // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of
400  // AbstractValueGraph) derives its behavior from calling successors().
401  private static final class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> {
402    private final ValueGraph<N, V> graph;
403
404    TransposedValueGraph(ValueGraph<N, V> graph) {
405      this.graph = graph;
406    }
407
408    @Override
409    ValueGraph<N, V> delegate() {
410      return graph;
411    }
412
413    @Override
414    public Set<N> predecessors(N node) {
415      return delegate().successors(node); // transpose
416    }
417
418    @Override
419    public Set<N> successors(N node) {
420      return delegate().predecessors(node); // transpose
421    }
422
423    @Override
424    public int inDegree(N node) {
425      return delegate().outDegree(node); // transpose
426    }
427
428    @Override
429    public int outDegree(N node) {
430      return delegate().inDegree(node); // transpose
431    }
432
433    @Override
434    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
435      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
436    }
437
438    @Override
439    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
440      return delegate().hasEdgeConnecting(transpose(endpoints));
441    }
442
443    @Override
444    public Optional<V> edgeValue(N nodeU, N nodeV) {
445      return delegate().edgeValue(nodeV, nodeU); // transpose
446    }
447
448    @Override
449    public Optional<V> edgeValue(EndpointPair<N> endpoints) {
450      return delegate().edgeValue(transpose(endpoints));
451    }
452
453    @Override
454    public @Nullable V edgeValueOrDefault(N nodeU, N nodeV, @Nullable V defaultValue) {
455      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
456    }
457
458    @Override
459    public @Nullable V edgeValueOrDefault(EndpointPair<N> endpoints, @Nullable V defaultValue) {
460      return delegate().edgeValueOrDefault(transpose(endpoints), defaultValue);
461    }
462  }
463
464  private static final class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
465    private final Network<N, E> network;
466
467    TransposedNetwork(Network<N, E> network) {
468      this.network = network;
469    }
470
471    @Override
472    Network<N, E> delegate() {
473      return network;
474    }
475
476    @Override
477    public Set<N> predecessors(N node) {
478      return delegate().successors(node); // transpose
479    }
480
481    @Override
482    public Set<N> successors(N node) {
483      return delegate().predecessors(node); // transpose
484    }
485
486    @Override
487    public int inDegree(N node) {
488      return delegate().outDegree(node); // transpose
489    }
490
491    @Override
492    public int outDegree(N node) {
493      return delegate().inDegree(node); // transpose
494    }
495
496    @Override
497    public Set<E> inEdges(N node) {
498      return delegate().outEdges(node); // transpose
499    }
500
501    @Override
502    public Set<E> outEdges(N node) {
503      return delegate().inEdges(node); // transpose
504    }
505
506    @Override
507    public EndpointPair<N> incidentNodes(E edge) {
508      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
509      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
510    }
511
512    @Override
513    public Set<E> edgesConnecting(N nodeU, N nodeV) {
514      return delegate().edgesConnecting(nodeV, nodeU); // transpose
515    }
516
517    @Override
518    public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
519      return delegate().edgesConnecting(transpose(endpoints));
520    }
521
522    @Override
523    public Optional<E> edgeConnecting(N nodeU, N nodeV) {
524      return delegate().edgeConnecting(nodeV, nodeU); // transpose
525    }
526
527    @Override
528    public Optional<E> edgeConnecting(EndpointPair<N> endpoints) {
529      return delegate().edgeConnecting(transpose(endpoints));
530    }
531
532    @Override
533    public @Nullable E edgeConnectingOrNull(N nodeU, N nodeV) {
534      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
535    }
536
537    @Override
538    public @Nullable E edgeConnectingOrNull(EndpointPair<N> endpoints) {
539      return delegate().edgeConnectingOrNull(transpose(endpoints));
540    }
541
542    @Override
543    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
544      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
545    }
546
547    @Override
548    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
549      return delegate().hasEdgeConnecting(transpose(endpoints));
550    }
551  }
552
553  // Graph copy methods
554
555  /**
556   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
557   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
558   * from {@code graph} for which both nodes are contained by {@code nodes}.
559   *
560   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
561   */
562  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
563    MutableGraph<N> subgraph =
564        (nodes instanceof Collection)
565            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
566            : GraphBuilder.from(graph).build();
567    for (N node : nodes) {
568      subgraph.addNode(node);
569    }
570    for (N node : subgraph.nodes()) {
571      for (N successorNode : graph.successors(node)) {
572        if (subgraph.nodes().contains(successorNode)) {
573          subgraph.putEdge(node, successorNode);
574        }
575      }
576    }
577    return subgraph;
578  }
579
580  /**
581   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
582   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
583   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
584   * nodes}.
585   *
586   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
587   */
588  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
589      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
590    MutableValueGraph<N, V> subgraph =
591        (nodes instanceof Collection)
592            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
593            : ValueGraphBuilder.from(graph).build();
594    for (N node : nodes) {
595      subgraph.addNode(node);
596    }
597    for (N node : subgraph.nodes()) {
598      for (N successorNode : graph.successors(node)) {
599        if (subgraph.nodes().contains(successorNode)) {
600          // requireNonNull is safe because the endpoint pair comes from the graph.
601          subgraph.putEdgeValue(
602              node,
603              successorNode,
604              requireNonNull(graph.edgeValueOrDefault(node, successorNode, null)));
605        }
606      }
607    }
608    return subgraph;
609  }
610
611  /**
612   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
613   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
614   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
615   * both contained by {@code nodes}.
616   *
617   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
618   */
619  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
620      Network<N, E> network, Iterable<? extends N> nodes) {
621    MutableNetwork<N, E> subgraph =
622        (nodes instanceof Collection)
623            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
624            : NetworkBuilder.from(network).build();
625    for (N node : nodes) {
626      subgraph.addNode(node);
627    }
628    for (N node : subgraph.nodes()) {
629      for (E edge : network.outEdges(node)) {
630        N successorNode = network.incidentNodes(edge).adjacentNode(node);
631        if (subgraph.nodes().contains(successorNode)) {
632          subgraph.addEdge(node, successorNode, edge);
633        }
634      }
635    }
636    return subgraph;
637  }
638
639  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
640  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
641    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
642    for (N node : graph.nodes()) {
643      copy.addNode(node);
644    }
645    for (EndpointPair<N> edge : graph.edges()) {
646      copy.putEdge(edge.nodeU(), edge.nodeV());
647    }
648    return copy;
649  }
650
651  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
652  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
653    MutableValueGraph<N, V> copy =
654        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
655    for (N node : graph.nodes()) {
656      copy.addNode(node);
657    }
658    for (EndpointPair<N> edge : graph.edges()) {
659      // requireNonNull is safe because the endpoint pair comes from the graph.
660      copy.putEdgeValue(
661          edge.nodeU(),
662          edge.nodeV(),
663          requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null)));
664    }
665    return copy;
666  }
667
668  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
669  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
670    MutableNetwork<N, E> copy =
671        NetworkBuilder.from(network)
672            .expectedNodeCount(network.nodes().size())
673            .expectedEdgeCount(network.edges().size())
674            .build();
675    for (N node : network.nodes()) {
676      copy.addNode(node);
677    }
678    for (E edge : network.edges()) {
679      EndpointPair<N> endpointPair = network.incidentNodes(edge);
680      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
681    }
682    return copy;
683  }
684
685  @CanIgnoreReturnValue
686  static int checkNonNegative(int value) {
687    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
688    return value;
689  }
690
691  @CanIgnoreReturnValue
692  static long checkNonNegative(long value) {
693    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
694    return value;
695  }
696
697  @CanIgnoreReturnValue
698  static int checkPositive(int value) {
699    checkArgument(value > 0, "Not true that %s is positive.", value);
700    return value;
701  }
702
703  @CanIgnoreReturnValue
704  static long checkPositive(long value) {
705    checkArgument(value > 0, "Not true that %s is positive.", value);
706    return value;
707  }
708
709  /**
710   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
711   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
712   * been already explored. Any node that has not been explored will not have a state at all.
713   */
714  private enum NodeVisitState {
715    PENDING,
716    COMPLETE
717  }
718}