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