9.1 Graphs¶
A graph is a nonlinear data structure made up of vertices and edges. We can represent a graph \(G\) abstractly using a set of vertices \(V\) and a set of edges \(E\). The following example describes a graph with 5 vertices and 7 edges.
If we think of vertices as nodes and edges as references (pointers) connecting those nodes, a graph can be viewed as an extension of a linked list. As Figure 9-1 shows, network relationships (graphs) allow more freedom than linear relationships (linked lists) or divide-and-conquer relationships (trees), making them more complex.
Figure 9-1 Relationships between linked lists, trees, and graphs
Description of Figure 9-1: Connection relationships in linked lists, trees, and graphs
Use the same five nodes to compare linear successors, hierarchical tree branches, and network relationships that permit cross-branch links and cycles.
From left to right, all three subfigures use five nodes numbered 1 through 5: arrows in the singly linked list and tree denote directed references, whereas line segments in the undirected graph denote two-way adjacency. These are side-by-side structural comparisons, not steps of an algorithm transforming one structure into another.
Comparing connection constraints from strictest to broadest: a singly linked list requires each non-tail node to have a single successor, forming one linear chain; a tree allows a parent node to branch to multiple child nodes in a top-down hierarchy from the root, while each non-root node still has only one parent with no cross-branch links or cycles; a graph removes root and hierarchy restrictions so any two vertices may be connected and cycles may occur.
Below the undirected "Graph" subfigure on the right, the note "Graphs allow the most flexible relationships and are therefore the most complex" refers to having the fewest connection constraints rather than the complexity of a specific algorithm. The table below lists the complete connections of all three structures.
| Structure | Complete connections | Connection constraints and features in this example |
|---|---|---|
| Singly linked list | 1→2, 2→3, 3→4, 4→5 | 4 successor references; single chain; tail node 5 has no successor |
| Tree | 1→2, 1→3, 2→4, 2→5 | 4 parent-child references; root is 1; leaves are 3, 4, 5 |
| Undirected graph | 1—2, 1—3, 1—5, 2—3, 2—4, 2—5, 4—5 | 7 undirected edges; contains cycles, not a complete graph |
The undirected graph in this example contains cycles such as 1—2—3—1 and 2—4—5—2, yet has no direct edge between 3 and 4 or between 3 and 5, so it is not a complete graph. Viewing nodes as vertices and references as edges lets us understand linked lists and trees from a graph perspective.
9.1.1 Common graph types and terminology¶
Depending on whether their edges have a direction, graphs are classified as undirected graphs or directed graphs, as shown in Figure 9-2.
- In an undirected graph, an edge represents a two-way connection between two vertices, such as a friendship on WeChat or QQ.
- In a directed graph, edges have a direction: the edges \(A \rightarrow B\) and \(A \leftarrow B\) are independent of each other. Examples include following and being followed on Weibo or Douyin.
Figure 9-2 Directed and undirected graphs
Description of Figure 9-2: Undirected and directed graphs: two-way undirected edges vs. independent directed edges
Contrast edge direction constraints on the same vertex layout using undirected segments and directed arrows.
Both the left and right figures contain five vertices numbered 1, 2, 3, 4, 5 in the exact same geometric layout (1 top-left, 3 bottom-left, 5 top-center, 2 bottom-center, 4 right) to contrast undirected and directed edges.
On the left is "Undirected graph (Edges have no direction)" with 7 arrowhead-free undirected edges: 1—2, 1—3, 1—5, 2—3, 2—4, 2—5, and 4—5. Every undirected edge inherently represents a two-way connection between two vertices; for example, edge 1—5 allows traversal both from 1 to 5 and from 5 to 1.
On the right is "Directed graph (Edges have a direction)" with 9 arrows, listed by tail vertex as 1→3, 2→1, 2→4, 2→5, 3→1, 3→2, 4→5, 5→1, and 5→4. Between vertices 1 and 3, and between 4 and 5, there is a pair of arrows in opposite directions, while the other five connections each have only a one-way arrow.
Directed edges in opposite directions are independent of one another. For instance, the right graph has 5→1 without a direct 1→5, although 5 is still indirectly reachable from 1 via 1→3→2→5. Direct two-way reachability requires two opposite directed edges; an indirect path must not be mistaken for a direct edge.
Depending on whether all vertices are connected, graphs are classified as connected graphs or disconnected graphs, as shown in Figure 9-3.
- In a connected graph, every other vertex can be reached from any starting vertex.
- In a disconnected graph, at least one vertex cannot be reached from a given starting vertex.
Figure 9-3 Connected and disconnected graphs
Description of Figure 9-3: Connected and disconnected graphs: all vertices reachable vs. an isolated vertex
Compare connectivity when all five vertices are mutually reachable versus when an isolated vertex is present.
Both the left and right figures show undirected graphs with vertices 1, 2, 3, 4, 5. An undirected graph is "connected" if starting from any vertex, every other vertex can be reached along a path of one or more edges; it does not require a direct edge between every pair of vertices.
On the left is "Connected graph (All vertices are mutually reachable)" with seven undirected edges: 1—2, 1—3, 1—5, 2—3, 2—4, 2—5, and 4—5. Even though vertices 3 and 4 have no direct edge, they can reach each other along path 3—2—4 or 3—1—5—4, so all five vertices form a single connected whole.
On the right is "Disconnected graph (Some vertices are unreachable from others)": it keeps the five undirected edges 1—2, 1—3, 1—5, 2—3, and 2—5 among the four vertices on the left, while removing the two edges 2—4 and 4—5 incident to vertex 4. Vertices 1, 2, 3, 5 remain mutually reachable among themselves, whereas no path reaches the isolated vertex 4 in the right figure.
The right graph splits into the connected subset {1, 2, 3, 5} and the isolated vertex {4}. Whenever at least one pair of vertices cannot reach each other along a path, the entire undirected graph is disconnected.
We can also assign a weight to each edge to obtain a weighted graph, as shown in Figure 9-4. For example, mobile games such as Honor of Kings calculate an affinity score between players based on the time they spend playing together. A weighted graph can represent this network of affinities.
Figure 9-4 Weighted and unweighted graphs
Description of Figure 9-4: Unweighted and weighted graphs: attaching numeric weights to edges
Attach numeric weights to the same set of connections to compare unweighted and weighted graphs.
Both the left and right figures contain vertices 1 through 5 and the same seven undirected edges, whose complete edge set is listed in the table below. On the left, "Unweighted graph (All edges are equivalent)" has no numeric labels on its edges; on the right, "Weighted graph (Edges have weights)" labels each edge with a decimal value.
"All edges are equivalent" means that existing edges are not distinguished by strength or length, not that every pair of vertices is connected. In the right figure, weights range from 0.2 to 1.0, with no physical unit specified in the drawing. The table below pairs each edge's numeric weight with its visual position in the figure.
| Edge | Weight | Position in figure |
|---|---|---|
| 1—2 | 0.5 | Center diagonal edge |
| 1—3 | 0.2 | Left vertical edge |
| 1—5 | 0.25 | Top edge |
| 2—3 | 0.3 | Bottom horizontal edge |
| 2—4 | 1.0 | Bottom-right diagonal edge |
| 2—5 | 0.7 | Center vertical edge |
| 4—5 | 0.88 | Top-right diagonal edge |
Adding weights does not change which vertices are connected by edges. Depending on the application, weights can represent quantities such as distance, cost, or affinity, supporting computations like shortest paths and minimum spanning trees.
The following terms are commonly used when discussing graphs.
- Adjacency: Two vertices are adjacent if an edge connects them. In Figure 9-4, the vertices adjacent to vertex 1 are 2, 3, and 5.
- Path: A sequence of edges followed from vertex A to vertex B is called a path from A to B. In Figure 9-4, the edge sequence 1-5-2-4 forms a path from vertex 1 to vertex 4.
- Degree: The number of edges incident to a vertex. In a directed graph, the in-degree is the number of edges pointing to the vertex, and the out-degree is the number of edges pointing away from it.
9.1.2 Representing a graph¶
Two common ways to represent a graph are an adjacency matrix and an adjacency list. We will use undirected graphs in the following examples.
1. Adjacency matrix¶
For a graph with \(n\) vertices, an adjacency matrix represents the graph using an \(n \times n\) matrix. Each row (or column) represents a vertex, and the matrix entries represent edges: \(1\) or \(0\) indicates whether an edge exists between two vertices.
As shown in Figure 9-5, let \(M\) be the adjacency matrix and \(V\) the vertex list. The entry \(M[i, j] = 1\) means that an edge connects vertices \(V[i]\) and \(V[j]\), whereas \(M[i, j] = 0\) means that no edge connects them.
Figure 9-5 Representing a graph with an adjacency matrix
Description of Figure 9-5: Adjacency matrix of an undirected graph
Map row and column indices through a vertex list and use each matrix cell to indicate whether an edge connects two vertices.
On the left is a five-vertex, seven-edge undirected graph, and on the right is its 5×5 adjacency matrix representation. The vertex list V = [1, 3, 2, 5, 4] maps in that order to row and column indices 0 through 4; vertex IDs and matrix indices must not be confused. The table headers list both index and vertex—find the corresponding indices first when looking up an edge.
In the adjacency matrix, entry M[i, j] = 1 indicates an edge between vertex V[i] at index i and vertex V[j] at index j, whereas M[i, j] = 0 indicates no edge. Because each edge in an undirected graph is equivalent in both directions, the same undirected connection is recorded as 1 at both M[i, j] and M[j, i], making the matrix symmetric about its main diagonal; since this graph has no self-loops, all main-diagonal entries M[i, i] are 0. Thus, the seven undirected edges correspond to 14 cells with value 1.
Color highlighting in the figure pairs three undirected edges with their symmetric matrix cells: edge 1—2 (indices 0 and 2) corresponds to M[0, 2] = 1 and M[2, 0] = 1; edge 3—2 (indices 1 and 2) corresponds to M[1, 2] = 1 and M[2, 1] = 1; and edge 5—4 (indices 3 and 4) corresponds to M[3, 4] = 1 and M[4, 3] = 1. The table below gives the complete matrix.
| Row: index / vertex | Column 0 / vertex 1 | Column 1 / vertex 3 | Column 2 / vertex 2 | Column 3 / vertex 5 | Column 4 / vertex 4 |
|---|---|---|---|---|---|
| 0/1 | 0 | 1 | 1 | 1 | 0 |
| 1/3 | 1 | 0 | 1 | 0 | 0 |
| 2/2 | 1 | 1 | 0 | 1 | 1 |
| 3/5 | 1 | 0 | 1 | 0 | 1 |
| 4/4 | 0 | 0 | 1 | 1 | 0 |
To check vertices 3 and 4, first locate their indices 1 and 4, then read M[1, 4] = 0 to see that no edge connects them. Do not use vertex IDs directly as matrix indices.
An adjacency matrix has the following properties.
- In a simple graph, a vertex cannot connect to itself, so the entries on the main diagonal do not represent meaningful connections.
- In an undirected graph, edges in the two directions are equivalent, so the adjacency matrix is symmetric about its main diagonal.
- Replacing the \(1\) and \(0\) entries with weights allows the matrix to represent a weighted graph.
With an adjacency matrix, we can access a matrix entry directly to retrieve an edge. Adding, removing, looking up, and modifying edges are therefore efficient, each taking \(O(1)\) time. However, the matrix requires \(O(n^2)\) space and uses a substantial amount of memory.
2. Adjacency list¶
An adjacency list represents a graph using \(n\) linked lists whose nodes represent vertices. The \(i\)-th linked list corresponds to vertex \(i\) and stores all of its adjacent vertices (the vertices connected to it). Figure 9-6 shows an example of a graph stored as an adjacency list.
Figure 9-6 Representing a graph with an adjacency list
Description of Figure 9-6: Adjacency list representation of a graph
Chain each vertex's neighbors into a horizontal linked list to represent the connections of the original graph.
The undirected graph on the left contains five vertices 1, 2, 3, 4, 5 and seven undirected edges 1—3, 1—5, 3—2, 2—5, 2—4, 5—4, and 1—2.
On the right under "Adjacency list", the left column labeled "Vertex" arranges five green head nodes from top to bottom in the order 1, 3, 2, 5, 4; from each row, a green linked list extends rightward under the label "All vertices adjacent to this vertex". The table below preserves the top-to-bottom row order shown in the figure.
Rightward arrows within a row represent only linked-list node references, not directed edges in the original graph; two neighbors adjacent in the same row are not necessarily directly connected in the graph either. Each undirected edge is recorded once in the adjacency list of each of its two endpoints, giving 14 neighbor nodes in total excluding the five head nodes in the left column.
| Vertex | Neighbors, in figure order |
|---|---|
| 1 | 2, 3, 5 |
| 3 | 1, 2 |
| 2 | 1, 3, 5, 4 |
| 5 | 1, 2, 4 |
| 4 | 2, 5 |
For example, undirected edge 1—2 corresponds to 2 in vertex 1's linked list and 1 in vertex 2's linked list; vertices 1 and 4 share no edge, so neither appears in the other's linked list.
An adjacency list stores only edges that actually exist. Since the total number of edges is usually much smaller than \(n^2\), it saves space. However, finding an edge requires traversing a linked list, so lookups are slower than with an adjacency matrix.
As Figure 9-6 shows, an adjacency list closely resembles separate chaining in a hash table, so similar techniques can improve its efficiency. For example, a long linked list can be replaced with an AVL tree or a red-black tree to improve lookup time from \(O(n)\) to \(O(\log n)\). Replacing it with a hash table can further reduce the time complexity to \(O(1)\).
9.1.3 Common applications of graphs¶
As shown in Table 9-1, many real-world systems can be modeled as graphs, and their associated problems can be reduced to graph computation problems.
Table 9-1 Common graphs in everyday life
| Vertices | Edges | Graph computation problem | |
|---|---|---|---|
| Social network | Users | Friendships | Recommending potential friends |
| Subway network | Stations | Connections between stations | Recommending the shortest route |
| Solar system | Celestial bodies | Gravitational interactions between bodies | Calculating planetary orbits |