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