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