mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-15 16:36:06 +00:00
build
This commit is contained in:
@@ -4,7 +4,7 @@ comments: true
|
||||
|
||||
# 9.1 Graph
|
||||
|
||||
A <u>graph</u> is a type of nonlinear data structure, consisting of <u>vertices</u> and <u>edges</u>. A graph $G$ can be abstractly represented as a collection of a set of vertices $V$ and a set of edges $E$. The following example shows a graph containing 5 vertices and 7 edges.
|
||||
A <u>graph</u> is a nonlinear data structure consisting of <u>vertices</u> and <u>edges</u>. We can abstractly represent a graph $G$ as a set of vertices $V$ and a set of edges $E$. The following example shows a graph containing 5 vertices and 7 edges.
|
||||
|
||||
$$
|
||||
\begin{aligned}
|
||||
@@ -14,33 +14,33 @@ G & = \{ V, E \} \newline
|
||||
\end{aligned}
|
||||
$$
|
||||
|
||||
If vertices are viewed as nodes and edges as references (pointers) connecting the nodes, graphs can be seen as a data structure that extends from linked lists. As shown in Figure 9-1, **compared to linear relationships (linked lists) and divide-and-conquer relationships (trees), network relationships (graphs) are more complex due to their higher degree of freedom**.
|
||||
If we view vertices as nodes and edges as references (pointers) connecting the nodes, we can see graphs as a data structure extended from linked lists. As shown in Figure 9-1, **compared to linear relationships (linked lists) and divide-and-conquer relationships (trees), network relationships (graphs) have a higher degree of freedom and are therefore more complex**.
|
||||
|
||||
{ class="animation-figure" }
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 9-1 Relationship between linked lists, trees, and graphs </p>
|
||||
<p align="center"> Figure 9-1 Relationships among linked lists, trees, and graphs </p>
|
||||
|
||||
## 9.1.1 Common types and terminologies of graphs
|
||||
## 9.1.1 Common Types and Terminology of Graphs
|
||||
|
||||
Graphs can be divided into <u>undirected graphs</u> and <u>directed graphs</u> depending on whether edges have direction, as shown in Figure 9-2.
|
||||
Graphs can be divided into <u>undirected graphs</u> and <u>directed graphs</u> based on whether edges have direction, as shown in Figure 9-2.
|
||||
|
||||
- In undirected graphs, edges represent a "bidirectional" connection between two vertices, for example, the "friends" in Facebook.
|
||||
- In directed graphs, edges have directionality, that is, the edges $A \rightarrow B$ and $A \leftarrow B$ are independent of each other. For example, the "follow" and "followed" relationship on Instagram or TikTok.
|
||||
- In undirected graphs, edges represent a "bidirectional" connection between two vertices, such as the "friend relationship" on WeChat or QQ.
|
||||
- In directed graphs, edges have directionality, meaning edges $A \rightarrow B$ and $A \leftarrow B$ are independent of each other, such as the "follow" and "be followed" relationships on Weibo or TikTok.
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 9-2 Directed and undirected graphs </p>
|
||||
|
||||
Depending on whether all vertices are connected, graphs can be divided into <u>connected graphs</u> and <u>disconnected graphs</u>, as shown in Figure 9-3.
|
||||
Graphs can be divided into <u>connected graphs</u> and <u>disconnected graphs</u> based on whether all vertices are connected, as shown in Figure 9-3.
|
||||
|
||||
- For connected graphs, it is possible to reach any other vertex starting from an arbitrary vertex.
|
||||
- For disconnected graphs, there is at least one vertex that cannot be reached from an arbitrary starting vertex.
|
||||
- For connected graphs, starting from any vertex, all other vertices can be reached.
|
||||
- For disconnected graphs, starting from a certain vertex, at least one vertex cannot be reached.
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 9-3 Connected and disconnected graphs </p>
|
||||
|
||||
We can also add a weight variable to edges, resulting in <u>weighted graphs</u> as shown in Figure 9-4. For example, in Instagram, the system sorts your follower and following list by the level of interaction between you and other users (likes, views, comments, etc.). Such an interaction network can be represented by a weighted graph.
|
||||
We can also add a "weight" variable to edges, resulting in <u>weighted graphs</u> as shown in Figure 9-4. For example, in mobile games like "Honor of Kings", the system calculates the "intimacy" between players based on their shared game time, and such intimacy networks can be represented using weighted graphs.
|
||||
|
||||
{ class="animation-figure" }
|
||||
|
||||
@@ -48,56 +48,56 @@ We can also add a weight variable to edges, resulting in <u>weighted graphs</u>
|
||||
|
||||
Graph data structures include the following commonly used terms.
|
||||
|
||||
- <u>Adjacency</u>: When there is an edge connecting two vertices, these two vertices are said to be "adjacent". In Figure 9-4, the adjacent vertices of vertex 1 are vertices 2, 3, and 5.
|
||||
- <u>Path</u>: The sequence of edges passed 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 is a path from vertex 1 to vertex 4.
|
||||
- <u>Degree</u>: The number of edges a vertex has. For directed graphs, <u>in-degree</u> refers to how many edges point to the vertex, and <u>out-degree</u> refers to how many edges point out from the vertex.
|
||||
- <u>Adjacency</u>: When two vertices are connected by an edge, these two vertices are said to be "adjacent". In Figure 9-4, the adjacent vertices of vertex 1 are vertices 2, 3, and 5.
|
||||
- <u>Path</u>: The sequence of edges 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 is a path from vertex 1 to vertex 4.
|
||||
- <u>Degree</u>: The number of edges a vertex has. For directed graphs, <u>in-degree</u> indicates how many edges point to the vertex, and <u>out-degree</u> indicates how many edges point out from the vertex.
|
||||
|
||||
## 9.1.2 Representation of graphs
|
||||
## 9.1.2 Representation of Graphs
|
||||
|
||||
Common representations of graphs include "adjacency matrix" and "adjacency list". The following examples use undirected graphs.
|
||||
Common representations of graphs include "adjacency matrices" and "adjacency lists". The following uses undirected graphs as examples.
|
||||
|
||||
### 1. Adjacency matrix
|
||||
### 1. Adjacency Matrix
|
||||
|
||||
Let the number of vertices in the graph be $n$, the <u>adjacency matrix</u> uses an $n \times n$ matrix to represent the graph, where each row (column) represents a vertex, and the matrix elements represent edges, with $1$ or $0$ indicating whether there is an edge between two vertices.
|
||||
Given a graph with $n$ vertices, an <u>adjacency matrix</u> uses an $n \times n$ matrix to represent the graph, where each row (column) represents a vertex, and matrix elements represent edges, using $1$ or $0$ to indicate whether an edge exists between two vertices.
|
||||
|
||||
As shown in Figure 9-5, let the adjacency matrix be $M$, and the list of vertices be $V$, then the matrix element $M[i, j] = 1$ indicates there is an edge between vertex $V[i]$ and vertex $V[j]$, conversely $M[i, j] = 0$ indicates there is no edge between the two vertices.
|
||||
As shown in Figure 9-5, let the adjacency matrix be $M$ and the vertex list be $V$. Then matrix element $M[i, j] = 1$ indicates that an edge exists between vertex $V[i]$ and vertex $V[j]$, whereas $M[i, j] = 0$ indicates no edge between the two vertices.
|
||||
|
||||
{ class="animation-figure" }
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 9-5 Representation of a graph with an adjacency matrix </p>
|
||||
<p align="center"> Figure 9-5 Adjacency matrix representation of a graph </p>
|
||||
|
||||
Adjacency matrices have the following characteristics.
|
||||
Adjacency matrices have the following properties.
|
||||
|
||||
- A vertex cannot be connected to itself, so the elements on the main diagonal of the adjacency matrix are meaningless.
|
||||
- For undirected graphs, edges in both directions are equivalent, thus the adjacency matrix is symmetric with regard to the main diagonal.
|
||||
- By replacing the elements of the adjacency matrix from $1$ and $0$ to weights, we can represent weighted graphs.
|
||||
- In simple graphs, vertices cannot connect to themselves, so the elements on the main diagonal of the adjacency matrix are meaningless.
|
||||
- For undirected graphs, edges in both directions are equivalent, so the adjacency matrix is symmetric about the main diagonal.
|
||||
- Replacing the elements of the adjacency matrix from $1$ and $0$ to weights allows representation of weighted graphs.
|
||||
|
||||
When representing graphs with adjacency matrices, it is possible to directly access matrix elements to obtain edges, resulting in efficient operations of addition, deletion, lookup, and modification, all with a time complexity of $O(1)$. However, the space complexity of the matrix is $O(n^2)$, which consumes more memory.
|
||||
When using adjacency matrices to represent graphs, we can directly access matrix elements to obtain edges, resulting in highly efficient addition, deletion, lookup, and modification operations, all with a time complexity of $O(1)$. However, the space complexity of the matrix is $O(n^2)$, which consumes significant memory.
|
||||
|
||||
### 2. Adjacency list
|
||||
### 2. Adjacency List
|
||||
|
||||
The <u>adjacency list</u> uses $n$ linked lists to represent the graph, with each linked list node representing a vertex. The $i$-th linked list corresponds to vertex $i$ and contains all adjacent vertices (vertices connected to that vertex). Figure 9-6 shows an example of a graph stored using an adjacency list.
|
||||
An <u>adjacency list</u> uses $n$ linked lists to represent a graph, with linked list nodes representing vertices. The $i$-th linked list corresponds to vertex $i$ and stores all adjacent vertices of that vertex (vertices connected to that vertex). Figure 9-6 shows an example of a graph stored using an adjacency list.
|
||||
|
||||
{ class="animation-figure" }
|
||||
{ class="animation-figure" }
|
||||
|
||||
<p align="center"> Figure 9-6 Representation of a graph with an adjacency list </p>
|
||||
<p align="center"> Figure 9-6 Adjacency list representation of a graph </p>
|
||||
|
||||
The adjacency list only stores actual edges, and the total number of edges is often much less than $n^2$, making it more space-efficient. However, finding edges in the adjacency list requires traversing the linked list, so its time efficiency is not as good as that of the adjacency matrix.
|
||||
Adjacency lists only store edges that actually exist, and the total number of edges is typically much less than $n^2$, making them more space-efficient. However, finding edges in an adjacency list requires traversing the linked list, so its time efficiency is inferior to that of adjacency matrices.
|
||||
|
||||
Observing Figure 9-6, **the structure of the adjacency list is very similar to the "chaining" in hash tables, hence we can use similar methods to optimize efficiency**. For example, when the linked list is long, it can be transformed into an AVL tree or red-black tree, thus optimizing the time efficiency from $O(n)$ to $O(\log n)$; the linked list can also be transformed into a hash table, thus reducing the time complexity to $O(1)$.
|
||||
Observing Figure 9-6, **the structure of adjacency lists is very similar to "chaining" in hash tables, so we can adopt similar methods to optimize efficiency**. For example, when linked lists are long, they can be converted to AVL trees or red-black trees, thereby optimizing time efficiency from $O(n)$ to $O(\log n)$; linked lists can also be converted to hash tables, thereby reducing time complexity to $O(1)$.
|
||||
|
||||
## 9.1.3 Common applications of graphs
|
||||
## 9.1.3 Common Applications of Graphs
|
||||
|
||||
As shown in Table 9-1, many real-world systems can be modeled with graphs, and corresponding problems can be reduced to graph computing problems.
|
||||
As shown in Table 9-1, many real-world systems can be modeled using graphs, and corresponding problems can be reduced to graph computation problems.
|
||||
|
||||
<p align="center"> Table 9-1 Common graphs in real life </p>
|
||||
|
||||
<div class="center-table" markdown>
|
||||
|
||||
| | Vertices | Edges | Graph Computing Problem |
|
||||
| --------------- | ---------------- | --------------------------------------------- | -------------------------------- |
|
||||
| Social Networks | Users | Follow / Followed | Potential Following Recommendations |
|
||||
| Subway Lines | Stations | Connectivity Between Stations | Shortest Route Recommendations |
|
||||
| Solar System | Celestial Bodies | Gravitational Forces Between Celestial Bodies | Planetary Orbit Calculations |
|
||||
| | Vertices | Edges | Graph Computation Problem |
|
||||
| -------------- | --------------- | -------------------------------------- | ----------------------------- |
|
||||
| Social network | Users | Friend relationships | Potential friend recommendation |
|
||||
| Subway lines | Stations | Connectivity between stations | Shortest route recommendation |
|
||||
| Solar system | Celestial bodies | Gravitational forces between celestial bodies | Planetary orbit calculation |
|
||||
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -9,13 +9,13 @@ icon: material/graphql
|
||||
|
||||
!!! abstract
|
||||
|
||||
In the journey of life, each of us is a node, connected by countless invisible edges.
|
||||
|
||||
Each encounter and parting leaves a unique imprint on this vast graph of life.
|
||||
In the journey of life, we are like nodes, connected by countless invisible edges.
|
||||
|
||||
Each encounter and parting leaves a unique mark on this vast network graph.
|
||||
|
||||
## Chapter contents
|
||||
|
||||
- [9.1 Graph](graph.md)
|
||||
- [9.2 Basic graph operations](graph_operations.md)
|
||||
- [9.3 Graph traversal](graph_traversal.md)
|
||||
- [9.2 Basic Operations on Graphs](graph_operations.md)
|
||||
- [9.3 Graph Traversal](graph_traversal.md)
|
||||
- [9.4 Summary](summary.md)
|
||||
|
||||
@@ -4,32 +4,32 @@ comments: true
|
||||
|
||||
# 9.4 Summary
|
||||
|
||||
### 1. Key review
|
||||
### 1. Key Review
|
||||
|
||||
- A graph is made up of vertices and edges. It can be described as a set of vertices and a set of edges.
|
||||
- Compared to linear relationships (like linked lists) and hierarchical relationships (like trees), network relationships (graphs) offer greater flexibility, making them more complex.
|
||||
- In a directed graph, edges have directions. In a connected graph, any vertex can be reached from any other vertex. In a weighted graph, each edge has an associated weight variable.
|
||||
- An adjacency matrix is a way to represent a graph using matrix (2D array). The rows and columns represent the vertices. The matrix element value indicates whether there is an edge between two vertices, using $1$ for an edge or $0$ for no edge. Adjacency matrices are highly efficient for operations like adding, deleting, or checking edges, but they require more space.
|
||||
- An adjacency list is another common way to represent a graph using a collection of linked lists. Each vertex in the graph has a list that contains all its adjacent vertices. The $i^{th}$ list represents vertex $i$. Adjacency lists use less space compared to adjacency matrices. However, since it requires traversing the list to find edges, the time efficiency is lower.
|
||||
- When the linked lists in an adjacency list are long enough, they can be converted into red-black trees or hash tables to improve lookup efficiency.
|
||||
- From the perspective of algorithmic design, an adjacency matrix reflects the concept of "trading space for time", whereas an adjacency list reflects "trading time for space".
|
||||
- Graphs can be used to model various real-world systems, such as social networks, subway routes.
|
||||
- A tree is a special case of a graph, and tree traversal is also a special case of graph traversal.
|
||||
- Breadth-first traversal of a graph is a search method that expands layer by layer from near to far, typically using a queue.
|
||||
- Depth-first traversal of a graph is a search method that prioritizes reaching the end before backtracking when no further path is available. It is often implemented using recursion.
|
||||
- Graphs consist of vertices and edges and can be represented as a set of vertices and a set of edges.
|
||||
- Compared to linear relationships (linked lists) and divide-and-conquer relationships (trees), network relationships (graphs) have a higher degree of freedom and are therefore more complex.
|
||||
- Directed graphs have edges with directionality, connected graphs have all vertices reachable from any vertex, and weighted graphs have edges that each contain a weight variable.
|
||||
- Adjacency matrices use matrices to represent graphs, where each row (column) represents a vertex, and matrix elements represent edges, using $1$ or $0$ to indicate whether two vertices have an edge or not. Adjacency matrices are highly efficient for addition, deletion, lookup, and modification operations, but consume significant space.
|
||||
- Adjacency lists use multiple linked lists to represent graphs, where the $i$-th linked list corresponds to vertex $i$ and stores all adjacent vertices of that vertex. Adjacency lists are more space-efficient than adjacency matrices, but have lower time efficiency because they require traversing linked lists to find edges.
|
||||
- When linked lists in adjacency lists become too long, they can be converted to red-black trees or hash tables, thereby improving lookup efficiency.
|
||||
- From an algorithmic perspective, adjacency matrices embody "trading space for time", while adjacency lists embody "trading time for space".
|
||||
- Graphs can be used to model various real-world systems, such as social networks and subway lines.
|
||||
- Trees are a special case of graphs, and tree traversal is a special case of graph traversal.
|
||||
- Breadth-first search of graphs is a near-to-far, layer-by-layer expansion search method, typically implemented using a queue.
|
||||
- Depth-first search of graphs is a search method that prioritizes going as far as possible and backtracks when no path remains, commonly implemented using recursion.
|
||||
|
||||
### 2. Q & A
|
||||
|
||||
**Q**: Is a path defined as a sequence of vertices or a sequence of edges?
|
||||
|
||||
In graph theory, a path in a graph is a finite or infinite sequence of edges which joins a sequence of vertices.
|
||||
The definitions in different language versions of Wikipedia are inconsistent: the English version states "a path is a sequence of edges", while the Chinese version states "a path is a sequence of vertices". The following is the original English text: In graph theory, a path in a graph is a finite or infinite sequence of edges which joins a sequence of vertices.
|
||||
|
||||
In this document, a path is considered a sequence of edges, rather than a sequence of vertices. This is because there might be multiple edges connecting two vertices, in which case each edge corresponds to a path.
|
||||
In this text, a path is viewed as a sequence of edges, not a sequence of vertices. This is because there may be multiple edges connecting two vertices, in which case each edge corresponds to a path.
|
||||
|
||||
**Q**: In a disconnected graph, are there points that cannot be traversed?
|
||||
**Q**: In a disconnected graph, will there be unreachable vertices?
|
||||
|
||||
In a disconnected graph, there is at least one vertex that cannot be reached from a specific point. To traverse a disconnected graph, you need to set multiple starting points to traverse all the connected components of the graph.
|
||||
In a disconnected graph, starting from a certain vertex, at least one vertex cannot be reached. Traversing a disconnected graph requires setting multiple starting points to traverse all connected components of the graph.
|
||||
|
||||
**Q**: In an adjacency list, does the order of "all vertices connected to that vertex" matter?
|
||||
**Q**: In an adjacency list, is there a requirement for the order of "all vertices connected to that vertex"?
|
||||
|
||||
It can be in any order. However, in real-world applications, it might be necessary to sort them according to certain rules, such as the order in which vertices are added, or the order of vertex values. This can help find vertices quickly with certain extreme values.
|
||||
It can be in any order. However, in practical applications, it may be necessary to sort according to specified rules, such as the order in which vertices were added, or the order of vertex values, which helps quickly find vertices "with certain extreme values".
|
||||
|
||||
Reference in New Issue
Block a user