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