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