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