1. Home
  2. Explore
  3. Computer Science
  4. Graph Data Structures in Java

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Graph Data Structures in Java

Graphs and Graph Algorithms

Graph fundamentals

A graph is a nonlinear data structure made of vertices and edges. A vertex—also called a node—holds data, while an edge represents a connection between two vertices. Graphs are useful for modeling networks and relationships that do not naturally fit into a simple linear sequence.

  • Vertex: A single node in the graph, such as a person, bus stop, or web page.

  • Edge: A connection between vertices, such as a friendship, bus route, or hyperlink.

  • Path: A sequence of vertices connected by edges. A path may contain intermediate vertices, or connect two vertices directly.

  • Cycle: A path that returns to a vertex it has already reached. Cycles make it especially important for search algorithms to track which vertices they have visited.

Graphs can model many real-world systems:

  • A neighborhood transportation network can use bus stops as vertices and routes as edges.

  • A web network can use pages as vertices and hyperlinks as edges.

  • A social network can use people as vertices and friendships as edges.

Directed and undirected graphs

An undirected graph represents connections that work in both directions. If two people are connected by an undirected friendship edge, each is connected to the other.

A directed graph uses edges with directions, often drawn as arrows. A directed edge from one vertex to another does not automatically imply an edge in the reverse direction. For example, a one-way route from one bus stop to another does not necessarily permit travel back along the same route.

Weighted and unweighted graphs

A weighted graph assigns a value, or weight, to each edge. The weight can represent distance, travel time, cost, or another quantity associated with moving between two vertices.

An unweighted graph treats all edges as having equal significance for the purposes of traversal. It may also be represented as a weighted graph whose edges all have the same weight.

Connectedness and disconnected graphs

Two vertices are connected if a path exists between them. A graph is disconnected if at least one pair of vertices has no path between them. A search that begins in one connected portion of a disconnected graph cannot reach vertices in another portion unless the search is restarted from an unvisited vertex.


Representing a graph in Java

A flexible graph implementation can use three cooperating classes:

  1. A vertex stores its data and its outgoing edges.

  2. An edge stores its start vertex, end vertex, and optionally its weight.

  3. A graph stores the vertices and the graph-wide properties, such as whether the graph is directed or weighted.

This arrangement represents a graph using an adjacency-list structure: each vertex keeps a list of the edges leaving it.

Vertex representation

A vertex can contain:

  • A data value, such as a stop name or person’s name.

  • A list of edges that begin at that vertex.

The vertex’s edge list records its neighbors indirectly through the edge objects. For instance, a vertex for a bus stop can have one outgoing edge for each stop it can reach directly.

Useful vertex operations include:

  • Add an edge: Create an edge from the current vertex to a specified end vertex, with an optional weight.

  • Remove an edge: Remove the edge leading to a specified end vertex.

  • Get data: Return the vertex’s stored value.

  • Get edges: Return the vertex’s outgoing-edge list.

When removing an edge, the implementation can search the edge list for an edge whose end vertex matches the requested vertex. In Java, a list operation such as removeIf can remove every element matching a predicate.

Edge representation

An edge stores:

  • Its start vertex.

  • Its end vertex.

  • Its weight, if the graph is weighted.

Using a nullable integer for an optional weight allows an unweighted edge to have no weight value, rather than requiring a special numeric placeholder. A clearer design can also distinguish “no weight” explicitly from a legitimate numeric weight.

Getter methods allow other classes to retrieve the start vertex, end vertex, and weight.

Graph representation and operations

The graph stores:

  • A list of all its vertices.

  • A Boolean property indicating whether it is weighted.

  • A Boolean property indicating whether it is directed.

Its constructor initializes the vertex list and records the chosen graph properties. Common graph operations include:

  • Add a vertex: Create a vertex containing the supplied data, add it to the graph’s vertex list, and return it so the caller can use it later.

  • Add an edge: Connect two vertices, applying the graph’s directed and weighted rules.

  • Remove an edge: Remove the requested connection.

  • Remove a vertex: Remove a vertex from the graph.

  • Get vertices: Return the graph’s vertex list.

  • Find a vertex by value: Search the list for a vertex whose stored data matches a requested value.

  • Inspect graph properties: Determine whether the graph is directed or weighted.

  • Print the graph: Display its vertices and edges to help verify the implementation.

For a directed graph, adding an edge from vertex uuu to vertex vvv adds only the connection u→vu \rightarrow vu→v. For an undirected graph, adding the connection must also add its reverse, v→uv \rightarrow uv→u. Removing an undirected edge likewise requires removing both directions.

When adding an edge to an unweighted graph, the implementation should ignore or normalize any supplied weight. When adding an edge to a weighted graph, it should preserve the supplied weight.

Removing a vertex safely requires removing its incident edges as well as removing it from the graph’s vertex list. Otherwise, other vertices may retain edges that point to a vertex no longer in the graph.

Example: a directed, weighted transportation network

A bus network can be represented as a directed, weighted graph:

  • Each bus stop is a vertex.

  • Each route from one stop to another is a directed edge.

  • Each edge’s weight can represent the distance or travel cost.

For example, if a route goes from Clifton to Cape May and has a weight of 100010001000, the graph stores an edge from the Clifton vertex to the Cape May vertex with that weight. If the graph is directed, this does not create a route back from Cape May to Clifton. That reverse route must be added separately if it exists.


Graph traversal and search

A graph traversal systematically visits vertices by following edges. Traversals can be used to search for a value, explore a component, or list vertices in a particular order.

Search algorithms must keep track of visited vertices. Without that record, an algorithm could visit the same vertex repeatedly. In a cyclic graph, repeatedly following edges without tracking visited vertices could cause an infinite loop.

The number of vertices is denoted by VVV, and the number of edges by EEE. When an algorithm examines each vertex and edge a bounded number of times, its running time is typically O(V+E)O(V + E)O(V+E).

Depth-first search

Depth-first search (DFS) follows one path as far as it can before backing up and exploring another path. It can be implemented recursively or with an explicit stack.

A recursive DFS follows this general process:

  1. Mark the current vertex as visited.

  2. Process its value, such as printing it or adding it to an output list.

  3. Examine each outgoing edge.

  4. For each neighbor that has not been visited, recursively search from that neighbor.

The visited collection is shared across recursive calls so that a vertex is not explored repeatedly.

DFS is useful for:

  • Searching for a vertex or a path.

  • Exploring a connected component.

  • Producing an ordered list of vertices.

  • Analyzing graph structure.

With an adjacency-list representation, a full traversal runs in O(V+E)O(V + E)O(V+E) time when each vertex and edge is examined a bounded number of times. A traversal beginning at one start vertex visits only the vertices reachable from that start.

DFS visitation orders

DFS can record vertices at different points in the traversal, producing different orders.

Preorder

In preorder, a vertex is added to the output when it is first reached, before recursively exploring its neighbors. The vertex is also marked visited at that point.

The exact preorder depends on the order in which neighbors are considered. If the traversal always chooses the smallest numbered available neighbor first, one example graph produces the order:

1,3,2,5,41, 3, 2, 5, 41,3,2,5,4

Postorder

In postorder, a vertex is added to the output after all of its unvisited neighbors have been explored—equivalently, when the vertex’s DFS call finishes.

For the same example, the postorder is:

5,2,4,3,15, 2, 4, 3, 15,2,4,3,1

Reverse postorder and topological order

Reverse postorder is the postorder list written in reverse:

1,3,4,2,51, 3, 4, 2, 51,3,4,2,5

For a directed acyclic graph (DAG), reverse postorder gives a topological ordering: an ordering in which each directed edge goes from an earlier vertex to a later vertex. A graph with a directed cycle has no topological ordering, so reverse postorder should not be treated as a valid topological sort for arbitrary directed graphs.

Breadth-first search

Breadth-first search (BFS) explores the graph in layers outward from a starting vertex:

  1. The first layer contains the starting vertex.

  2. The next layer contains its direct neighbors.

  3. The following layer contains previously unseen neighbors of the vertices in the second layer.

  4. The process continues until no reachable vertices remain.

BFS uses a queue rather than recursion or a stack. A queue processes vertices in first-in, first-out order.

A typical BFS proceeds as follows:

  1. Mark the starting vertex as visited and enqueue it.

  2. While the queue is not empty:

    • Dequeue the next vertex.

    • Process its value.

    • Examine each outgoing edge.

    • For every unvisited neighbor, mark it visited and enqueue it.

Marking a neighbor visited when it is enqueued prevents the same vertex from being added to the queue multiple times. As with DFS, the visited collection prevents repeated work and infinite cycling.

For an unweighted graph, BFS finds a path with the fewest edges from the start vertex to any reachable vertex. With an adjacency-list representation, a full traversal runs in O(V+E)O(V + E)O(V+E) time.

Comparing DFS and BFS

  • DFS: Explores one branch deeply before returning to another branch. It can use recursion or a stack.

  • BFS: Explores all vertices at one distance from the start before moving farther away. It uses a queue.

  • Both: Need a visited collection, can search reachable parts of a graph, and run in O(V+E)O(V + E)O(V+E) time when each vertex and edge is examined a bounded number of times.

  • Shortest paths: BFS finds shortest paths by edge count in an unweighted graph. DFS does not generally guarantee a shortest path.

Example traversal

Suppose a directed graph starts at vertex 111, whose neighbors are 333 and 444. Suppose the traversal visits the smaller numbered neighbor first, and the remaining connections lead to vertices 222 and 555.

  • A DFS preorder can be 1,3,2,5,41, 3, 2, 5, 41,3,2,5,4 because it follows one branch before returning to explore another.

  • A BFS order can be 1,3,4,2,51, 3, 4, 2, 51,3,4,2,5 because it visits both direct neighbors of 111 before visiting vertices farther away.

The difference comes from the traversal strategy, not from a difference in the graph.


Dijkstra’s shortest-path algorithm

Dijkstra’s algorithm finds shortest-path distances from one starting vertex to other vertices in a weighted graph. It is useful for problems such as finding a shortest travel route or determining the least-cost route through a network.

Dijkstra’s algorithm requires nonnegative edge weights. Negative weights can invalidate its greedy choice: a vertex treated as having its final shortest distance might later be reachable by a cheaper path containing a negative edge.

Unlike DFS and BFS, Dijkstra’s algorithm is not simply a traversal order. It repeatedly chooses the currently known closest unprocessed vertex and uses that vertex to improve distance estimates for its neighbors.

Distance estimates and relaxation

The algorithm maintains a tentative distance from the starting vertex to each vertex:

  • The starting vertex has distance 000.

  • Other vertices initially have distance ∞\infty∞, meaning that no route has been found yet.

  • When a shorter route is discovered, the tentative distance is updated.

For a current vertex uuu and an outgoing edge to vvv with weight w(u,v)w(u,v)w(u,v), the route through uuu has length:

d(u)+w(u,v)d(u) + w(u,v)d(u)+w(u,v)

If this candidate route is shorter than the current estimate for vvv, the algorithm updates the distance:

d(v)←min⁡(d(v), d(u)+w(u,v))d(v) \leftarrow \min\bigl(d(v),\ d(u) + w(u,v)\bigr)d(v)←min(d(v), d(u)+w(u,v))

This update is called relaxing an edge. A predecessor record is also updated so the route can later be reconstructed.

Priority queue approach

A priority queue retrieves the queued item with the smallest priority. For Dijkstra’s algorithm, each queued item contains a vertex and its current tentative distance.

The algorithm proceeds as follows:

  1. Set the start vertex’s distance to 000 and all other distances to ∞\infty∞.

  2. Add the start vertex to the priority queue with priority 000.

  3. Remove the vertex with the smallest tentative distance.

  4. Examine each outgoing edge from that vertex and relax it.

  5. Whenever a neighbor’s distance improves, update its predecessor and add its new distance to the priority queue.

  6. Continue until the queue is empty or the required target has been settled.

A practical implementation may place the same vertex in the queue more than once as its distance improves. When an older queue entry is removed, it should be ignored if its priority no longer matches the best known distance. Alternatively, the implementation can use a settled set to ensure each vertex is finalized only once.

Example: finding shortest distances from AAA

Consider a directed graph with these weighted connections:

  • A→BA \rightarrow BA→B has weight 444.

  • A→CA \rightarrow CA→C has weight 222.

  • B→CB \rightarrow CB→C has weight 111.

  • B→EB \rightarrow EB→E has weight 333.

  • B→DB \rightarrow DB→D has weight 222.

  • C→EC \rightarrow EC→E has weight 111.

  • E→DE \rightarrow DE→D has weight 555.

Initially, the distances are d(A)=0d(A)=0d(A)=0 and d(B)=d(C)=d(D)=d(E)=∞d(B)=d(C)=d(D)=d(E)=\inftyd(B)=d(C)=d(D)=d(E)=∞.

  1. Process AAA. Its edges give d(B)=4d(B)=4d(B)=4 and d(C)=2d(C)=2d(C)=2.

  2. Process CCC. It is the closest unprocessed vertex, with distance 222. The route to EEE through CCC has length 2+1=32+1=32+1=3, so d(E)=3d(E)=3d(E)=3.

  3. Process EEE. Its route to DDD has length 3+5=83+5=83+5=8, so d(D)=8d(D)=8d(D)=8.

  4. Process BBB. Its route to CCC has length 4+1=54+1=54+1=5, which is worse than the existing distance 222. Its route to EEE has length 4+3=74+3=74+3=7, worse than 333. Its route to DDD has length 4+2=64+2=64+2=6, improving the existing estimate 888 to 666.

  5. Process DDD. No further improvement is possible.

The shortest distances from AAA are therefore:

  • To AAA: 000

  • To BBB: 444

  • To CCC: 222

  • To DDD: 666

  • To EEE: 333

The shortest route from AAA to DDD is A→B→DA \rightarrow B \rightarrow DA→B→D, with total weight 666. The direct route found earlier through EEE has total weight 888, so it is not optimal.

Data structures for a Java implementation

A Java implementation can use the following structures:

  • A map from vertex identifiers or data values to tentative distances.

  • A map from each vertex to its predecessor vertex on the best-known route.

  • A priority queue of vertex-distance entries.

For example, distances can be represented as a mapping from a vertex’s string value to an integer distance, while predecessors map a vertex’s value to a vertex. A special value such as null can represent “no predecessor,” which is appropriate for the start vertex.

A custom priority-queue entry can store:

  • The vertex.

  • Its priority, corresponding to the tentative distance.

The entry comparison operation orders entries by increasing priority, allowing the queue to return the smallest distance first.

When computing an alternative distance, the implementation adds the current vertex’s known distance to the edge weight. It then compares the result with the neighbor’s stored distance. If the alternative is smaller, it updates both the distance and predecessor and queues the neighbor with its improved priority.

An implementation should avoid adding an edge weight to an infinity sentinel such as Java’s maximum integer value. It should also handle unreachable vertices: their distances remain infinite, and they have no predecessor on a route from the start.

Reconstructing a shortest path

The distance map gives the minimum total weight but does not by itself show the route. The predecessor map makes route reconstruction possible:

  1. Begin at the target vertex.

  2. Follow its predecessor to the vertex immediately before it.

  3. Continue following predecessors until reaching the starting vertex.

  4. Reverse the collected sequence to obtain the path from start to target.

For example, if the predecessor chain for DDD is D←B←AD \leftarrow B \leftarrow AD←B←A, reversing it gives A→B→DA \rightarrow B \rightarrow DA→B→D.

If the target has no predecessor and is not the starting vertex, it is unreachable from the start. A shortest-path display should report that no path exists rather than presenting an incomplete route.

Complexity

With a priority queue and an adjacency-list graph, Dijkstra’s algorithm is commonly implemented in:

O((V+E)log⁡V)O\bigl((V+E)\log V\bigr)O((V+E)logV)

A version using a different priority-queue implementation or graph assumptions may report a closely related bound, such as O(E+Vlog⁡V)O(E + V\log V)O(E+VlogV). The exact bound depends on the priority-queue operations and implementation details. The algorithm’s correctness still depends on nonnegative edge weights.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent