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