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