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.Queue;
037import java.util.Set;
038import javax.annotation.CheckForNull;
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 */
047@Beta
048@ElementTypesAreNonnullByDefault
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    @CheckForNull 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, @CheckForNull 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    @CheckForNull
402    public V edgeValueOrDefault(N nodeU, N nodeV, @CheckForNull V defaultValue) {
403      return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose
404    }
405
406    @Override
407    @CheckForNull
408    public V edgeValueOrDefault(EndpointPair<N> endpoints, @CheckForNull V defaultValue) {
409      return delegate().edgeValueOrDefault(transpose(endpoints), defaultValue);
410    }
411  }
412
413  private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> {
414    private final Network<N, E> network;
415
416    TransposedNetwork(Network<N, E> network) {
417      this.network = network;
418    }
419
420    @Override
421    Network<N, E> delegate() {
422      return network;
423    }
424
425    @Override
426    public Set<N> predecessors(N node) {
427      return delegate().successors(node); // transpose
428    }
429
430    @Override
431    public Set<N> successors(N node) {
432      return delegate().predecessors(node); // transpose
433    }
434
435    @Override
436    public int inDegree(N node) {
437      return delegate().outDegree(node); // transpose
438    }
439
440    @Override
441    public int outDegree(N node) {
442      return delegate().inDegree(node); // transpose
443    }
444
445    @Override
446    public Set<E> inEdges(N node) {
447      return delegate().outEdges(node); // transpose
448    }
449
450    @Override
451    public Set<E> outEdges(N node) {
452      return delegate().inEdges(node); // transpose
453    }
454
455    @Override
456    public EndpointPair<N> incidentNodes(E edge) {
457      EndpointPair<N> endpointPair = delegate().incidentNodes(edge);
458      return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose
459    }
460
461    @Override
462    public Set<E> edgesConnecting(N nodeU, N nodeV) {
463      return delegate().edgesConnecting(nodeV, nodeU); // transpose
464    }
465
466    @Override
467    public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
468      return delegate().edgesConnecting(transpose(endpoints));
469    }
470
471    @Override
472    @CheckForNull
473    public E edgeConnectingOrNull(N nodeU, N nodeV) {
474      return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose
475    }
476
477    @Override
478    @CheckForNull
479    public E edgeConnectingOrNull(EndpointPair<N> endpoints) {
480      return delegate().edgeConnectingOrNull(transpose(endpoints));
481    }
482
483    @Override
484    public boolean hasEdgeConnecting(N nodeU, N nodeV) {
485      return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose
486    }
487
488    @Override
489    public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
490      return delegate().hasEdgeConnecting(transpose(endpoints));
491    }
492  }
493
494  // Graph copy methods
495
496  /**
497   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
498   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
499   * from {@code graph} for which both nodes are contained by {@code nodes}.
500   *
501   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
502   */
503  public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) {
504    MutableGraph<N> subgraph =
505        (nodes instanceof Collection)
506            ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
507            : GraphBuilder.from(graph).build();
508    for (N node : nodes) {
509      subgraph.addNode(node);
510    }
511    for (N node : subgraph.nodes()) {
512      for (N successorNode : graph.successors(node)) {
513        if (subgraph.nodes().contains(successorNode)) {
514          subgraph.putEdge(node, successorNode);
515        }
516      }
517    }
518    return subgraph;
519  }
520
521  /**
522   * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph
523   * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges}
524   * (and associated edge values) from {@code graph} for which both nodes are contained by {@code
525   * nodes}.
526   *
527   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
528   */
529  public static <N, V> MutableValueGraph<N, V> inducedSubgraph(
530      ValueGraph<N, V> graph, Iterable<? extends N> nodes) {
531    MutableValueGraph<N, V> subgraph =
532        (nodes instanceof Collection)
533            ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build()
534            : ValueGraphBuilder.from(graph).build();
535    for (N node : nodes) {
536      subgraph.addNode(node);
537    }
538    for (N node : subgraph.nodes()) {
539      for (N successorNode : graph.successors(node)) {
540        if (subgraph.nodes().contains(successorNode)) {
541          // requireNonNull is safe because the endpoint pair comes from the graph.
542          subgraph.putEdgeValue(
543              node,
544              successorNode,
545              requireNonNull(graph.edgeValueOrDefault(node, successorNode, null)));
546        }
547      }
548    }
549    return subgraph;
550  }
551
552  /**
553   * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph
554   * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges}
555   * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are
556   * both contained by {@code nodes}.
557   *
558   * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph
559   */
560  public static <N, E> MutableNetwork<N, E> inducedSubgraph(
561      Network<N, E> network, Iterable<? extends N> nodes) {
562    MutableNetwork<N, E> subgraph =
563        (nodes instanceof Collection)
564            ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build()
565            : NetworkBuilder.from(network).build();
566    for (N node : nodes) {
567      subgraph.addNode(node);
568    }
569    for (N node : subgraph.nodes()) {
570      for (E edge : network.outEdges(node)) {
571        N successorNode = network.incidentNodes(edge).adjacentNode(node);
572        if (subgraph.nodes().contains(successorNode)) {
573          subgraph.addEdge(node, successorNode, edge);
574        }
575      }
576    }
577    return subgraph;
578  }
579
580  /** Creates a mutable copy of {@code graph} with the same nodes and edges. */
581  public static <N> MutableGraph<N> copyOf(Graph<N> graph) {
582    MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
583    for (N node : graph.nodes()) {
584      copy.addNode(node);
585    }
586    for (EndpointPair<N> edge : graph.edges()) {
587      copy.putEdge(edge.nodeU(), edge.nodeV());
588    }
589    return copy;
590  }
591
592  /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */
593  public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
594    MutableValueGraph<N, V> copy =
595        ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build();
596    for (N node : graph.nodes()) {
597      copy.addNode(node);
598    }
599    for (EndpointPair<N> edge : graph.edges()) {
600      // requireNonNull is safe because the endpoint pair comes from the graph.
601      copy.putEdgeValue(
602          edge.nodeU(),
603          edge.nodeV(),
604          requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null)));
605    }
606    return copy;
607  }
608
609  /** Creates a mutable copy of {@code network} with the same nodes and edges. */
610  public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) {
611    MutableNetwork<N, E> copy =
612        NetworkBuilder.from(network)
613            .expectedNodeCount(network.nodes().size())
614            .expectedEdgeCount(network.edges().size())
615            .build();
616    for (N node : network.nodes()) {
617      copy.addNode(node);
618    }
619    for (E edge : network.edges()) {
620      EndpointPair<N> endpointPair = network.incidentNodes(edge);
621      copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge);
622    }
623    return copy;
624  }
625
626  @CanIgnoreReturnValue
627  static int checkNonNegative(int value) {
628    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
629    return value;
630  }
631
632  @CanIgnoreReturnValue
633  static long checkNonNegative(long value) {
634    checkArgument(value >= 0, "Not true that %s is non-negative.", value);
635    return value;
636  }
637
638  @CanIgnoreReturnValue
639  static int checkPositive(int value) {
640    checkArgument(value > 0, "Not true that %s is positive.", value);
641    return value;
642  }
643
644  @CanIgnoreReturnValue
645  static long checkPositive(long value) {
646    checkArgument(value > 0, "Not true that %s is positive.", value);
647    return value;
648  }
649
650  /**
651   * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on
652   * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have
653   * been already explored. Any node that has not been explored will not have a state at all.
654   */
655  private enum NodeVisitState {
656    PENDING,
657    COMPLETE
658  }
659}