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 com.google.common.annotations.Beta;
020import com.google.errorprone.annotations.DoNotMock;
021import java.util.Collection;
022import java.util.Set;
023import javax.annotation.CheckForNull;
024
025/**
026 * An interface for <a
027 * href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data,
028 * whose edges are anonymous entities with no identity or information of their own.
029 *
030 * <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes.
031 *
032 * <p>There are three primary interfaces provided to represent graphs. In order of increasing
033 * complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally
034 * prefer the simplest interface that satisfies your use case. See the <a
035 * href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type">
036 * "Choosing the right graph type"</a> section of the Guava User Guide for more details.
037 *
038 * <h3>Capabilities</h3>
039 *
040 * <p>{@code Graph} supports the following use cases (<a
041 * href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of
042 * terms</a>):
043 *
044 * <ul>
045 *   <li>directed graphs
046 *   <li>undirected graphs
047 *   <li>graphs that do/don't allow self-loops
048 *   <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered
049 * </ul>
050 *
051 * <p>{@code Graph} explicitly does not support parallel edges, and forbids implementations or
052 * extensions with parallel edges. If you need parallel edges, use {@link Network}.
053 *
054 * <h3>Building a {@code Graph}</h3>
055 *
056 * <p>The implementation classes that {@code common.graph} provides are not public, by design. To
057 * create an instance of one of the built-in implementations of {@code Graph}, use the {@link
058 * GraphBuilder} class:
059 *
060 * <pre>{@code
061 * MutableGraph<Integer> graph = GraphBuilder.undirected().build();
062 * }</pre>
063 *
064 * <p>{@link GraphBuilder#build()} returns an instance of {@link MutableGraph}, which is a subtype
065 * of {@code Graph} that provides methods for adding and removing nodes and edges. If you do not
066 * need to mutate a graph (e.g. if you write a method than runs a read-only algorithm on the graph),
067 * you should use the non-mutating {@link Graph} interface, or an {@link ImmutableGraph}.
068 *
069 * <p>You can create an immutable copy of an existing {@code Graph} using {@link
070 * ImmutableGraph#copyOf(Graph)}:
071 *
072 * <pre>{@code
073 * ImmutableGraph<Integer> immutableGraph = ImmutableGraph.copyOf(graph);
074 * }</pre>
075 *
076 * <p>Instances of {@link ImmutableGraph} do not implement {@link MutableGraph} (obviously!) and are
077 * contractually guaranteed to be unmodifiable and thread-safe.
078 *
079 * <p>The Guava User Guide has <a
080 * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more
081 * information on (and examples of) building graphs</a>.
082 *
083 * <h3>Additional documentation</h3>
084 *
085 * <p>See the Guava User Guide for the {@code common.graph} package (<a
086 * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for
087 * additional documentation, including:
088 *
089 * <ul>
090 *   <li><a
091 *       href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence">
092 *       {@code equals()}, {@code hashCode()}, and graph equivalence</a>
093 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization">
094 *       Synchronization policy</a>
095 *   <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes
096 *       for implementors</a>
097 * </ul>
098 *
099 * @author James Sexton
100 * @author Joshua O'Madadhain
101 * @param <N> Node parameter type
102 * @since 20.0
103 */
104@Beta
105@DoNotMock("Use GraphBuilder to create a real instance")
106public interface Graph<N> extends BaseGraph<N> {
107  //
108  // Graph-level accessors
109  //
110
111  /** Returns all nodes in this graph, in the order specified by {@link #nodeOrder()}. */
112  @Override
113  Set<N> nodes();
114
115  /** Returns all edges in this graph. */
116  @Override
117  Set<EndpointPair<N>> edges();
118
119  //
120  // Graph properties
121  //
122
123  /**
124   * Returns true if the edges in this graph are directed. Directed edges connect a {@link
125   * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while
126   * undirected edges connect a pair of nodes to each other.
127   */
128  @Override
129  boolean isDirected();
130
131  /**
132   * Returns true if this graph allows self-loops (edges that connect a node to itself). Attempting
133   * to add a self-loop to a graph that does not allow them will throw an {@link
134   * IllegalArgumentException}.
135   */
136  @Override
137  boolean allowsSelfLoops();
138
139  /** Returns the order of iteration for the elements of {@link #nodes()}. */
140  @Override
141  ElementOrder<N> nodeOrder();
142
143  /**
144   * Returns an {@link ElementOrder} that specifies the order of iteration for the elements of
145   * {@link #edges()}, {@link #adjacentNodes(Object)}, {@link #predecessors(Object)}, {@link
146   * #successors(Object)} and {@link #incidentEdges(Object)}.
147   *
148   * @since 29.0
149   */
150  @Override
151  ElementOrder<N> incidentEdgeOrder();
152
153  //
154  // Element-level accessors
155  //
156
157  /**
158   * Returns a live view of the nodes which have an incident edge in common with {@code node} in
159   * this graph.
160   *
161   * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}.
162   *
163   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
164   * {@code view} returned by this method will be invalidated, and will throw {@code
165   * IllegalStateException} if it is accessed in any way, with the following exceptions:
166   *
167   * <ul>
168   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
169   *       expression involving {@code view} will throw)
170   *   <li>{@code hashCode()} does not throw
171   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
172   *       behavior is undefined
173   * </ul>
174   *
175   * @throws IllegalArgumentException if {@code node} is not an element of this graph
176   */
177  @Override
178  Set<N> adjacentNodes(N node);
179
180  /**
181   * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
182   * traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge.
183   *
184   * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
185   *
186   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
187   * {@code view} returned by this method will be invalidated, and will throw {@code
188   * IllegalStateException} if it is accessed in any way, with the following exceptions:
189   *
190   * <ul>
191   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
192   *       expression involving {@code view} will throw)
193   *   <li>{@code hashCode()} does not throw
194   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
195   *       behavior is undefined
196   * </ul>
197   *
198   * @throws IllegalArgumentException if {@code node} is not an element of this graph
199   */
200  @Override
201  Set<N> predecessors(N node);
202
203  /**
204   * Returns a live view of all nodes in this graph adjacent to {@code node} which can be reached by
205   * traversing {@code node}'s outgoing edges in the direction (if any) of the edge.
206   *
207   * <p>In an undirected graph, this is equivalent to {@link #adjacentNodes(Object)}.
208   *
209   * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing
210   * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}.
211   *
212   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
213   * {@code view} returned by this method will be invalidated, and will throw {@code
214   * IllegalStateException} if it is accessed in any way, with the following exceptions:
215   *
216   * <ul>
217   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
218   *       expression involving {@code view} will throw)
219   *   <li>{@code hashCode()} does not throw
220   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
221   *       behavior is undefined
222   * </ul>
223   *
224   * @throws IllegalArgumentException if {@code node} is not an element of this graph
225   */
226  @Override
227  Set<N> successors(N node);
228
229  /**
230   * Returns a live view of the edges in this graph whose endpoints include {@code node}.
231   *
232   * <p>This is equal to the union of incoming and outgoing edges.
233   *
234   * <p>If {@code node} is removed from the graph after this method is called, the {@code Set}
235   * {@code view} returned by this method will be invalidated, and will throw {@code
236   * IllegalStateException} if it is accessed in any way, with the following exceptions:
237   *
238   * <ul>
239   *   <li>{@code view.equals(view)} evaluates to {@code true} (but any other {@code equals()}
240   *       expression involving {@code view} will throw)
241   *   <li>{@code hashCode()} does not throw
242   *   <li>if {@code node} is re-added to the graph after having been removed, {@code view}'s
243   *       behavior is undefined
244   * </ul>
245   *
246   * @throws IllegalArgumentException if {@code node} is not an element of this graph
247   * @since 24.0
248   */
249  @Override
250  Set<EndpointPair<N>> incidentEdges(N node);
251
252  /**
253   * Returns the count of {@code node}'s incident edges, counting self-loops twice (equivalently,
254   * the number of times an edge touches {@code node}).
255   *
256   * <p>For directed graphs, this is equal to {@code inDegree(node) + outDegree(node)}.
257   *
258   * <p>For undirected graphs, this is equal to {@code incidentEdges(node).size()} + (number of
259   * self-loops incident to {@code node}).
260   *
261   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
262   *
263   * @throws IllegalArgumentException if {@code node} is not an element of this graph
264   */
265  @Override
266  int degree(N node);
267
268  /**
269   * Returns the count of {@code node}'s incoming edges (equal to {@code predecessors(node).size()})
270   * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
271   *
272   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
273   *
274   * @throws IllegalArgumentException if {@code node} is not an element of this graph
275   */
276  @Override
277  int inDegree(N node);
278
279  /**
280   * Returns the count of {@code node}'s outgoing edges (equal to {@code successors(node).size()})
281   * in a directed graph. In an undirected graph, returns the {@link #degree(Object)}.
282   *
283   * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}.
284   *
285   * @throws IllegalArgumentException if {@code node} is not an element of this graph
286   */
287  @Override
288  int outDegree(N node);
289
290  /**
291   * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is
292   * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}.
293   *
294   * <p>In an undirected graph, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}.
295   *
296   * @since 23.0
297   */
298  @Override
299  boolean hasEdgeConnecting(N nodeU, N nodeV);
300
301  /**
302   * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if
303   * any, specified by {@code endpoints}). This is equivalent to {@code
304   * edges().contains(endpoints)}.
305   *
306   * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the
307   * endpoints are unordered and the graph is directed; it simply returns {@code false}. This is for
308   * consistency with the behavior of {@link Collection#contains(Object)} (which does not generally
309   * throw if the object cannot be present in the collection), and the desire to have this method's
310   * behavior be compatible with {@code edges().contains(endpoints)}.
311   *
312   * @since 27.1
313   */
314  @Override
315  boolean hasEdgeConnecting(EndpointPair<N> endpoints);
316
317  //
318  // Graph identity
319  //
320
321  /**
322   * Returns {@code true} iff {@code object} is a {@link Graph} that has the same elements and the
323   * same structural relationships as those in this graph.
324   *
325   * <p>Thus, two graphs A and B are equal if <b>all</b> of the following are true:
326   *
327   * <ul>
328   *   <li>A and B have equal {@link #isDirected() directedness}.
329   *   <li>A and B have equal {@link #nodes() node sets}.
330   *   <li>A and B have equal {@link #edges() edge sets}.
331   * </ul>
332   *
333   * <p>Graph properties besides {@link #isDirected() directedness} do <b>not</b> affect equality.
334   * For example, two graphs may be considered equal even if one allows self-loops and the other
335   * doesn't. Additionally, the order in which nodes or edges are added to the graph, and the order
336   * in which they are iterated over, are irrelevant.
337   *
338   * <p>A reference implementation of this is provided by {@link AbstractGraph#equals(Object)}.
339   */
340  @Override
341  boolean equals(@CheckForNull Object object);
342
343  /**
344   * Returns the hash code for this graph. The hash code of a graph is defined as the hash code of
345   * the set returned by {@link #edges()}.
346   *
347   * <p>A reference implementation of this is provided by {@link AbstractGraph#hashCode()}.
348   */
349  @Override
350  int hashCode();
351}