This chapter covers graphs. Graphs are a versatile way of representing connections between objects. In this chapter, you will learn graph basics, including fundamental terminology and graph types. The chapter will also cover working with these different graph types and methods of representing graphs in data structures that have already been explored. Finally, algorithms for traversing, searching, and sorting graphs are explored to solve problems such as finding the shortest path between two graph nodes.
Graph Basics
Examples of Graph Applications
Application | Item | Connection |
---|---|---|
Web site | Web page | Links |
Map | Intersection | Road |
Circuit | Component | Wiring |
Social media | Person | “Friendship”/connection |
Telephone | Phone number | Landline |

Two examples of graphs
Vertex: A vertex is the node from which graphs are formed. In this chapter, a node will be noted as V for Big-O analysis. A vertex is represented using a circle, as shown in Figure 17-2.
Edge: An edge is the connection between nodes in a graph. Graphically, it is the “line” between the vertices. It will be noted as E for Big-O analysis. An edge is represented using a line, as shown in Figure 17-2.

Vertices and edges
Degree of vertex: The degree of a vertex refers to the number of edges on that vertex (node).
Sparse graph: A graph is considered sparse when only a small fraction of possible connections exist between vertices (see Figure 17-3).

Sparse graph
Dense graph: A graph is considered dense when there are a lot of connections between different vertices (see Figure 17-4).

Dense graph
Cyclical graph: A directed graph is considered cyclical if there is a path that travels from a vertex and back to itself. For example, in Figure 17-5, B can follow the edge to C and then D and then E and then to B again.

Graph with a cycle on B

Graph without a cycle
Weights: Weights are values on the edges. Weights can signify various things depending on the context. For example, weights on a directed graph can represent the distance required to get from node A to B, as shown in Figure 17-7.

Directed graph with weights
Undirected Graphs

Undirected graph with weights

Graph (left), adjacency list (middle), and adjacency matrix (right)
So far, the concepts and definitions of graphs have been discussed. Now, let’s actually start implementing these ideas into code and learn how to add and remove edges and vertices.
Adding Edges and Vertices

The first undirected graph
Removing Edges and Vertices
Continuing with the same example, let’s implement the functions for removing edges and vertices for the graph class.

Vertex 5 removed

Vertex 1 removed

Edge between 2 and 3 removed
Directed Graphs

Directed graph
In this example, the E node can “travel” to the D node, and the D node can travel only to the C node.

Adding A to B

Adding B to C

Adding C to A
Graph Traversal
A graph can be traversed in multiple ways. The two most common approaches are breadth-first search and depth-first search. Similarly to how different tree traversal techniques were explored, this section will focus on these two traversal techniques and when to use each of them.
Breadth-First Search

Level-order traversal for binary search tree

Breadth-first search graph
Similar to the level-order traversal for the tree data structure, a queue is needed for a BFS.
Time Complexity: O(V + E)
The time complexity is O(V + E), where V is the number of vertices and E is the number of edges. This is because the algorithm has to go through every edge and node to traverse the whole graph.

The earlier undirected graph example
Applying the BFS to the graph, the following is printed: 1, 2, 5, 3, 4.

Breadth-first search, part 1

Breadth-first search, part 2
Depth-First Search
Depth-first search (DFS) refers to a search algorithm in a graph that focuses on traversing deep into one connection before visiting the other connections.

Post-order traversal

Depth-first search graph
Notice how E is visited last. This is because the search visits all the nodes connected to C in depth before visiting E.
Similar to the pre-post, and in-order traversal for the tree data structure, recursion is used to go deep into a node until that path is exhausted.
Time Complexity: O(V + E)
The time complexity is O(V + E) where V is the number of vertices and E is the number of edges. This is because the algorithm has to go through every edge and node to traverse the whole graph. This is the same time complexity as the BFS algorithm.

The earlier graph example from Figure 17-20
Applying the DFS to the graph, the following is printed: 1, 2, 3, 4, 5.

Depth-first search, part 1

Depth-first search, part 2
Weighted Graphs and Shortest Path
Now that we have covered the basics of graphs and how to traverse them, we can discuss weighted edges and Dijkstra’s algorithm, which employs shortest path searches.
Graphs with Weighted Edges
Recall that edges in a graph represent a connection between the vertices. If edges establish a connection, weight can be assigned to that connection. For example, for a graph that represents a map, the weights on the edges are distances.

Graph representation of five cities
The most important question for weighted edge graphs is, what is the shortest path from one node to another? There are series of shortest path algorithms for graphs. The one we discuss is Dijkstra’s algorithm.
Dijkstra’s Algorithm: Shortest Path

Dijkstra stage 1: everything marked as infinity

Dijkstra stage 2: B and C processed

Dijkstra stage 3: all nodes now processed
Time Complexity: O(V2 + E)
The algorithm here is similar to the BFS algorithm but requires the _extractMin method , which is O(n) in time complexity. Because of this, the time complexity is O(V2 + E) because all neighbor vertices of the node currently being traversed have to be checked during the _extractMin method. This algorithm can be improved using a priority queue for the extract min, which would yield O(log2(V )) _extractMin and hence yield an overall time complexity of O(E + V) * O(log2(V)) = O(E log2(V)). This can be even more optimized by using a Fibonacci heap, which has constant time to compute _extractMin. However, for simplicity, neither a Fibonacci heap nor a priority queue was used for this demonstration.
Topological Sort
For a directed graph, it can be important to know which node should be processed first for various applications. An example of this is a task scheduler where one task depends on a previous task being done. Another example is a JavaScript library dependency manager where it has to figure out which libraries to import before others. The topological sorting algorithm implements this. It is a modified DFS that uses a stack to record the order.

Topological sort
Time Complexity: O(V + E)
Space Complexity: O(V)
The topological sort algorithm is simply DFS with an extra stack. Therefore, the time complexity is the same as DFS. Topological sorting requires O(V) in space because it needs to store all the vertices in the stack. This algorithm is powerful for scheduling jobs from given dependencies.
Summary
This chapter discussed different types of graphs, their properties, and how to search and sort them. A graph, composed of vertices and connected via edges, can be represented as a data structure in many different ways. In this chapter, an adjacency list was used to represent the graph. If the graph is dense, it is better to use a matrix-based representation of a graph instead. In a graph’s edges, weights signify the importance (or the lack thereof) of the connected vertices. Moreover, by assigning weights to edges, Dijkstra’s shortest path algorithm was implemented. Finally, graphs are versatile data structures with various use cases and interesting algorithms.
Graph Properties Summary
Property | Description |
---|---|
Dense | There are a lot of connections between different vertices. |
Sparse | Only a small fraction of possible connections exist between vertices. |
Cyclical | There is a path that takes vertices back to themselves. |
Uncyclical | There is a no path such that vertices can be taken back to themselves. |
Directed | Graphs have a direction between edges. |
Undirected | Graphs do not have a direction between edges. |
Graph Algorithm Summary
Algorithm | Description/Use Case | Time Complexity |
---|---|---|
BFS | Traverses the graph by visiting neighbor nodes one level at a time | O(V + E ) |
DFS | Traverses the graph by going deep into each neighbor node one at a time | O(V + E ) |
Dijkstra | Finds the shortest path from one vertex to the rest of the other vertices | O(V2+ E ) |
Topological Sort | Sorts the directed graph; for job scheduling algorithms | O(V + E ) |