Graph Data Structures in Java


Graph Data Structures in Java

Michael
Welcome to Coding Cleverly. Today we’re building up a practical understanding of graphs: what they represent, how to model them in Java, and how three important algorithms—depth-first search, breadth-first search, and Dijkstra’s algorithm—help us explore them.

Hope
Let’s begin with the basic picture. A graph is a nonlinear data structure made of vertices and edges. A vertex is a node that holds data, and an edge is a connection between vertices.

Michael
That simple structure can represent a lot of real-world networks. In a neighborhood transportation graph, for example, bus stops could be vertices and bus routes between stops could be edges. Web pages and hyperlinks, or people and friendships, can be modeled the same way.

Hope
The friendship example also helps distinguish directed from undirected graphs. If Peter and Jordan are connected by a friendship that goes both ways, that connection is undirected. If a connection only points from Peter to Jordan, it’s directed.

Michael
Edges can also carry weights. A weight might represent a distance, cost, or another number associated with traveling along that connection. So a bus route could connect two stops and have a distance as its weight.

Hope
And a graph doesn’t have to be all connected. A path is a sequence of vertices joined through edges, possibly with intermediate vertices. If there’s no path between two vertices, they’re disconnected from each other; a graph with separated groups like that is called disconnected.

Michael
Now let’s turn that picture into a Java design. The course separates the implementation into three classes: Vertex, Edge, and Graph. The vertex stores its data and its outgoing edge instances, while the graph stores the vertices.

Hope
An edge records where it starts, where it ends, and—if the graph is weighted—its weight. The vertex can add an edge to a neighbor or remove edges leading to a particular neighbor. Helper methods let other classes retrieve the vertex’s data and its edge list.

Michael
In the example implementation, a vertex has a string for its data and an ArrayList of edges. Its constructor stores the supplied data and initializes that list. An edge’s constructor stores its start vertex, end vertex, and weight, and getters expose those values.

Hope
The weight is represented with Java’s Integer rather than the primitive int so it can be null when no weight is supplied. That gives the implementation a way to represent an unweighted connection without using a special numeric value.

Michael
The Graph class then keeps an ArrayList of vertices and two settings: whether the graph is weighted and whether it’s directed. The constructor receives those settings, initializes the vertex list, and stores the choices.

Hope
Adding a vertex means creating a Vertex with the requested data, adding it to the graph’s list, and returning it. Returning the vertex is useful because the caller can keep that reference and use it later when adding connections.

Michael
The graph’s add-edge method takes a start vertex, an end vertex, and a weight. If the graph is unweighted, the implementation uses null for the weight. It adds the forward edge, and if the graph is undirected, it adds the reverse edge too.

Hope
That reverse edge is the key detail: an undirected connection needs to be represented in both directions so each endpoint can reach the other. A directed graph only gets the forward edge. Removing an edge follows the same idea—remove the forward connection, and remove the reverse one as well if the graph is undirected.

Michael
The Graph class also provides operations for removing a vertex, getting the vertex list, checking whether the graph is weighted or directed, finding a vertex by its data value, and printing the graph. The search-by-value method checks the stored vertices and returns a match, or null if there isn’t one.

Hope
There is an important design point here: callers can use the graph’s add-edge and remove-edge methods without having to manage the underlying edge lists themselves. That layer of abstraction keeps graph operations in the Graph class and edge details in the Vertex and Edge classes.

Michael
The demonstration builds a bus network with two stops, Clifton and Cape May. It creates a weighted, directed graph, adds the stops, and connects Clifton to Cape May with a weight of 1,000. Printing the graph shows that one-way connection and its weight.

Hope
Because that example is directed, the reverse route isn’t automatically present. If the graph were made undirected instead, adding that connection would create the reverse connection too. So the graph’s settings affect how its edges behave.

Michael
Once a graph is modeled, we can search it. A graph search explores vertices, often to find a particular value or path. The two traversal approaches emphasized here are depth-first search, or DFS, and breadth-first search, or BFS.

Hope
Both need to keep track of visited vertices. Without that record, a search could revisit the same vertex repeatedly. In a graph with cycles, that can even lead to an infinite loop.

Michael
DFS explores one route as far as it can before backing up to try another. In the recursive version, you visit the current vertex, examine its neighboring edges, and recursively explore any neighbor that hasn’t been visited yet.

Hope
The example starts at vertex 1 and chooses the smaller-numbered option whenever there’s a choice. It visits 1, then 3, then 2, then 5. When that branch runs out, it backs up and visits 4. That gives the pre-order visitation sequence 1, 3, 2, 5, 4.

Michael
Pre-order means a vertex is recorded before its descendants are explored. The course also describes post-order, where a vertex is recorded after its descendants have been explored and it is popped from the stack. For the example graph, that produces 5, 2, 4, 3, 1.

Hope
Reverse post-order is exactly the reverse of that post-order list. For this example, it’s 1, 3, 4, 2, 5. The material also refers to this reverse order as topological sorting, and presents these orders as different ways to organize a graph traversal.

Michael
BFS explores in layers instead of following one path deeply. It starts with the origin and its direct neighbors, then moves outward to neighbors of those vertices. That’s why BFS uses a queue: vertices wait their turn to be explored in the order they were added.

Hope
Using the same example and the same preference for smaller numbers, BFS visits 1 first, then its direct neighbors 3 and 4. It then explores the next layer, finding 2 from 3 and later 5 from 2. The resulting order is 1, 3, 4, 2, 5.

Michael
So DFS and BFS can visit the same reachable vertices but in different orders. In the Java versions, DFS uses recursion, while BFS uses a queue. Both share the visited-vertices list so cycles or shared neighbors don’t cause repeated processing.

Hope
For both searches, the upper-bound runtime described is O of V plus E: V is the number of vertices and E is the number of edges. The reason is that, in the upper-bound case, the search examines the vertices and edges of the graph.

Michael
There’s another use for traversal besides looking for a particular path: collecting all the vertex values in an organized order. DFS can provide visitation sequences such as pre-order, post-order, and reverse post-order, depending on when vertices are recorded.

Hope
Now let’s move from exploring a graph to finding distances. A common problem is determining the shortest route between vertices—for example, the best route to a destination, or a route through a computer network. The algorithm presented for this is Dijkstra’s algorithm.

Michael
The walkthrough begins at A. The distance from A to itself is zero, and the distances to the other vertices are initially treated as infinity. Each iteration selects the unvisited vertex with the smallest known distance, then checks whether traveling through it gives a shorter distance to its neighbors.

Hope
In the example, A connects to B with weight 4 and to C with weight 2. Those become the current best distances from A. Next, C is selected because its distance, 2, is the smallest unvisited distance. C connects to E with weight 1, so the route A to C to E has total distance 3.

Michael
Then E is selected, and its edge to D has weight 5. That gives a tentative distance of 8 to D. Later, B is selected with distance 4. From B, the route to C would total 5, which is worse than C’s existing distance of 2. The route to E would total 7, worse than its existing distance of 3.

Hope
But B’s edge to D has weight 2, so the route A to B to D totals 6. Since 6 improves on the earlier tentative distance of 8, the distance to D is updated. When D is selected and has no more neighbors to process, the walkthrough has found the distances from A to the other vertices.

Michael
The core operation is called relaxing an edge: take the current distance to a vertex, add the edge’s weight, and compare that alternative distance with the best one already recorded for the neighbor. If the alternative is smaller, update the neighbor’s distance.

Hope
The Java implementation keeps a distance dictionary that maps vertex data to its current distance. It also keeps a previous-vertex dictionary, which records how each vertex was reached. Together, those let the program report both distances and paths.

Michael
For selecting the next vertex efficiently, the implementation uses a priority queue of queue objects. Each object holds a vertex and a priority based on its current distance. The queue makes it possible to remove the smallest-priority item next.

Hope
At setup, the starting vertex is given distance zero and placed in the priority queue. Other vertices start with a maximum integer value, used as the implementation’s stand-in for infinity, and their previous-vertex entries start as null.

Michael
Then, while the priority queue isn’t empty, the algorithm removes the vertex with the smallest priority. For each outgoing edge, it calculates the alternative distance. If that’s better than the stored distance for the neighbor, it updates the distance and records the current vertex as the neighbor’s previous vertex.

Hope
The neighbor is also added to the priority queue with its updated distance. Repeating that process updates the distance dictionary and previous-vertex dictionary. The implementation returns both so other methods can use the results.

Michael
To reconstruct a shortest path, the example starts at the target and follows the previous-vertex links backward. Each vertex is inserted at the beginning of a path list, so the final list reads from the starting vertex to the target rather than backward.

Hope
That lets the program print the shortest distance and the route itself. In the example, the reported route from A to G is A to D to E to G, with the distance shown by the accumulated weights in the graph.

Michael
The stated runtime for the priority-queue version is O of E plus V log V, where E is the number of edges and V is the number of vertices. That’s the efficiency target given for this implementation.

Hope
So the big picture is: vertices hold data, edges describe connections, and graph settings control direction and weights. DFS goes deep before backing up, BFS explores in layers, and Dijkstra repeatedly improves distance estimates to find shortest routes.

Michael
And the implementation choices match those ideas: lists store vertices and edges, a visited list prevents repeated traversal, a stack-like recursive process supports DFS, a queue supports BFS, and a priority queue plus distance and previous maps supports Dijkstra. With those pieces, graphs become a flexible way to model and explore networks.

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