diff --git a/codes/java/chapter_graph/graph_adjacency_list.java b/codes/java/chapter_graph/graph_adjacency_list.java index a1ca10173..481fa7b98 100644 --- a/codes/java/chapter_graph/graph_adjacency_list.java +++ b/codes/java/chapter_graph/graph_adjacency_list.java @@ -7,19 +7,13 @@ package chapter_graph; import java.util.*; - -/* 顶点类 */ -class Vertex { - int val; - public Vertex(int val) { - this.val = val; - } -} +import include.*; /* 基于邻接表实现的无向图类 */ class GraphAdjList { - // 请注意,vertices 和 adjList 中存储的都是 Vertex 对象 - Map> adjList; // 邻接表(使用哈希表实现) + // 邻接表,使用哈希表来代替链表,以提升删除边、删除顶点的效率 + // 请注意,adjList 中的元素是 Vertex 对象 + Map> adjList; /* 构造方法 */ public GraphAdjList(Vertex[][] edges) { @@ -59,26 +53,26 @@ class GraphAdjList { public void addVertex(Vertex vet) { if (adjList.containsKey(vet)) return; - // 在邻接表中添加一个新链表(即 HashSet) - adjList.put(vet, new HashSet<>()); + // 在邻接表中添加一个新链表 + adjList.put(vet, new ArrayList<>()); } /* 删除顶点 */ public void removeVertex(Vertex vet) { if (!adjList.containsKey(vet)) throw new IllegalArgumentException(); - // 在邻接表中删除顶点 vet 对应的链表(即 HashSet) + // 在邻接表中删除顶点 vet 对应的链表 adjList.remove(vet); - // 遍历其它顶点的链表(即 HashSet),删除所有包含 vet 的边 - for (Set set : adjList.values()) { - set.remove(vet); + // 遍历其它顶点的链表,删除所有包含 vet 的边 + for (List list : adjList.values()) { + list.remove(vet); } } /* 打印邻接表 */ public void print() { System.out.println("邻接表 ="); - for (Map.Entry> entry : adjList.entrySet()) { + for (Map.Entry> entry : adjList.entrySet()) { List tmp = new ArrayList<>(); for (Vertex vertex : entry.getValue()) tmp.add(vertex.val); @@ -90,25 +84,21 @@ class GraphAdjList { public class graph_adjacency_list { public static void main(String[] args) { /* 初始化无向图 */ - Vertex v0 = new Vertex(1), - v1 = new Vertex(3), - v2 = new Vertex(2), - v3 = new Vertex(5), - v4 = new Vertex(4); - Vertex[][] edges = { { v0, v1 }, { v1, v2 }, { v2, v3 }, { v0, v3 }, { v2, v4 }, { v3, v4 } }; + Vertex[] v = Vertex.valsToVets(new int[] { 1, 3, 2, 5, 4 }); + Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[2], v[3] }, { v[2], v[4] }, { v[3], v[4] } }; GraphAdjList graph = new GraphAdjList(edges); System.out.println("\n初始化后,图为"); graph.print(); /* 添加边 */ - // 顶点 1, 2 即 v0, v2 - graph.addEdge(v0, v2); + // 顶点 1, 2 即 v[0], v[2] + graph.addEdge(v[0], v[2]); System.out.println("\n添加边 1-2 后,图为"); graph.print(); /* 删除边 */ - // 顶点 1, 3 即 v0, v1 - graph.removeEdge(v0, v1); + // 顶点 1, 3 即 v[0], v[1] + graph.removeEdge(v[0], v[1]); System.out.println("\n删除边 1-3 后,图为"); graph.print(); @@ -119,8 +109,8 @@ public class graph_adjacency_list { graph.print(); /* 删除顶点 */ - // 顶点 3 即 v1 - graph.removeVertex(v1); + // 顶点 3 即 v[1] + graph.removeVertex(v[1]); System.out.println("\n删除顶点 3 后,图为"); graph.print(); } diff --git a/codes/java/chapter_graph/graph_adjacency_matrix.java b/codes/java/chapter_graph/graph_adjacency_matrix.java index 5c7edb15c..bf054ca97 100644 --- a/codes/java/chapter_graph/graph_adjacency_matrix.java +++ b/codes/java/chapter_graph/graph_adjacency_matrix.java @@ -100,7 +100,7 @@ public class graph_adjacency_matrix { /* 初始化无向图 */ // 请注意,edges 元素代表顶点索引,即对应 vertices 元素索引 int[] vertices = { 1, 3, 2, 5, 4 }; - int[][] edges = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 0, 3 }, { 2, 4 }, { 3, 4 } }; + int[][] edges = { { 0, 1 }, { 0, 3 }, { 1, 2 }, { 2, 3 }, { 2, 4 }, { 3, 4 } }; GraphAdjMat graph = new GraphAdjMat(vertices, edges); System.out.println("\n初始化后,图为"); graph.print(); diff --git a/codes/java/chapter_graph/graph_bfs.java b/codes/java/chapter_graph/graph_bfs.java new file mode 100644 index 000000000..45c481d46 --- /dev/null +++ b/codes/java/chapter_graph/graph_bfs.java @@ -0,0 +1,53 @@ +/** + * File: graph_bfs.java + * Created Time: 2023-02-12 + * Author: Krahets (krahets@163.com) + */ + +package chapter_graph; + +import java.util.*; +import include.*; + +public class graph_bfs { + /* 广度优先遍历 BFS */ + // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 + static List graphBFS(GraphAdjList graph, Vertex startVet) { + // 顶点遍历序列 + List res = new ArrayList<>(); + // 哈希表,用于记录已被访问过的顶点 + Set visited = new HashSet<>() {{ add(startVet); }}; + // 队列用于实现 BFS + Queue que = new LinkedList<>() {{ offer(startVet); }}; + // 以顶点 vet 为起点,循环直至访问完所有顶点 + while (!que.isEmpty()) { + Vertex vet = que.poll(); // 队首顶点出队 + res.add(vet); // 记录访问顶点 + // 遍历该顶点的所有邻接顶点 + for (Vertex adjVet : graph.adjList.get(vet)) { + if (visited.contains(adjVet)) + continue; // 跳过已被访问过的顶点 + que.offer(adjVet); // 只入队未访问的顶点 + visited.add(adjVet); // 标记该顶点已被访问 + } + } + // 返回顶点遍历序列 + return res; + } + + public static void main(String[] args) { + /* 初始化无向图 */ + Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[1], v[4] }, + { v[2], v[5] }, { v[3], v[4] }, { v[3], v[6] }, { v[4], v[5] }, + { v[4], v[7] }, { v[5], v[8] }, { v[6], v[7] }, { v[7], v[8] } }; + GraphAdjList graph = new GraphAdjList(edges); + System.out.println("\n初始化后,图为"); + graph.print(); + + /* 广度优先遍历 BFS */ + List res = graphBFS(graph, v[0]); + System.out.println("\n广度优先遍历(BFS)顶点序列为"); + System.out.println(Vertex.vetsToVals(res)); + } +} diff --git a/codes/java/chapter_graph/graph_dfs.java b/codes/java/chapter_graph/graph_dfs.java new file mode 100644 index 000000000..1c542f423 --- /dev/null +++ b/codes/java/chapter_graph/graph_dfs.java @@ -0,0 +1,51 @@ +/** + * File: graph_dfs.java + * Created Time: 2023-02-12 + * Author: Krahets (krahets@163.com) + */ + +package chapter_graph; + +import java.util.*; +import include.*; + +public class graph_dfs { + /* 深度优先遍历 DFS 辅助函数 */ + static void dfs(GraphAdjList graph, Set visited, List res, Vertex vet) { + res.add(vet); // 记录访问顶点 + visited.add(vet); // 标记该顶点已被访问 + // 遍历该顶点的所有邻接顶点 + for (Vertex adjVet : graph.adjList.get(vet)) { + if (visited.contains(adjVet)) + continue; // 跳过已被访问过的顶点 + // 递归访问邻接顶点 + dfs(graph, visited, res, adjVet); + } + } + + /* 深度优先遍历 DFS */ + // 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点 + static List graphDFS(GraphAdjList graph, Vertex startVet) { + // 顶点遍历序列 + List res = new ArrayList<>(); + // 哈希表,用于记录已被访问过的顶点 + Set visited = new HashSet<>(); + dfs(graph, visited, res, startVet); + return res; + } + + public static void main(String[] args) { + /* 初始化无向图 */ + Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6 }); + Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, + { v[2], v[5] }, { v[4], v[5] }, { v[5], v[6] } }; + GraphAdjList graph = new GraphAdjList(edges); + System.out.println("\n初始化后,图为"); + graph.print(); + + /* 深度优先遍历 BFS */ + List res = graphDFS(graph, v[0]); + System.out.println("\n深度优先遍历(DFS)顶点序列为"); + System.out.println(Vertex.vetsToVals(res)); + } +} diff --git a/codes/java/chapter_graph/graph_traversal.java b/codes/java/chapter_graph/graph_traversal.java new file mode 100644 index 000000000..3b152198d --- /dev/null +++ b/codes/java/chapter_graph/graph_traversal.java @@ -0,0 +1,70 @@ +/** + * File: graph_adjacency_list.java + * Created Time: 2023-02-12 + * Author: Krahets (krahets@163.com) + */ + +package chapter_graph; + +import java.util.*; + +public class graph_traversal { + /* 以顶点 vet 为起点,对图 graph 执行广度优先遍历 */ + // 采用 GraphAdjList 表示图,以方便获取指定结点的所有邻接结点 + static List graphBFS(GraphAdjList graph, Vertex startVet) { + // 顶点遍历序列 + List res = new ArrayList<>(); + // 用于记录顶点是否已被访问 + Set visited = new HashSet<>() {{ add(startVet); }}; + // 队列用于实现 BFS + Queue que = new LinkedList<>() {{ offer(startVet); }}; + // 循环直至访问完所有顶点 + while (!que.isEmpty()) { + Vertex vet = que.poll(); // 队首顶点出队 + res.add(vet); // 访问该顶点 + // 遍历该顶点的所有邻接顶点 + for (Vertex adjVet : graph.adjList.get(vet)) { + if (!visited.contains(adjVet)) { + que.offer(adjVet); // 只入队未访问的顶点 + visited.add(adjVet); // 标记该顶点已被访问 + } + } + } + // 返回顶点遍历序列 + return res; + } + + /* 输入值列表 vals ,返回顶点列表 vets */ + static Vertex[] valsToVets(int[] vals) { + Vertex[] vets = new Vertex[vals.length]; + for (int i = 0; i < vals.length; i++) { + vets[i] = new Vertex(vals[i]); + } + return vets; + } + + /* 输入顶点列表 vets ,返回值列表 vals */ + static List vetsToVals(List vets) { + List vals = new ArrayList<>(); + for (Vertex vet : vets) { + vals.add(vet.val); + } + return vals; + } + + public static void main(String[] args) { + /* 初始化无向图 */ + Vertex[] v = valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[1], v[4] }, + { v[2], v[5] }, { v[3], v[4] }, { v[3], v[6] }, { v[4], v[5] }, + { v[4], v[7] }, { v[5], v[8] }, { v[6], v[7] }, { v[7], v[8] }}; + GraphAdjList graph = new GraphAdjList(edges); + System.out.println("\n初始化后,图为"); + graph.print(); + + /* 广度优先遍历 BFS */ + List res = graphBFS(graph, v[0]); + System.out.println("\n广度优先遍历(BFS)顶点序列为"); + System.out.println(vetsToVals(res)); + } +} diff --git a/codes/java/include/Vertex.java b/codes/java/include/Vertex.java new file mode 100644 index 000000000..80c59cfd8 --- /dev/null +++ b/codes/java/include/Vertex.java @@ -0,0 +1,35 @@ +/** + * File: TreeNode.java + * Created Time: 2022-11-25 + * Author: Krahets (krahets@163.com) + */ + +package include; + +import java.util.*; + +/* 顶点类 */ +public class Vertex { + public int val; + public Vertex(int val) { + this.val = val; + } + + /* 输入值列表 vals ,返回顶点列表 vets */ + public static Vertex[] valsToVets(int[] vals) { + Vertex[] vets = new Vertex[vals.length]; + for (int i = 0; i < vals.length; i++) { + vets[i] = new Vertex(vals[i]); + } + return vets; + } + + /* 输入顶点列表 vets ,返回值列表 vals */ + public static List vetsToVals(List vets) { + List vals = new ArrayList<>(); + for (Vertex vet : vets) { + vals.add(vet.val); + } + return vals; + } +} \ No newline at end of file diff --git a/docs/chapter_array_and_linkedlist/array.md b/docs/chapter_array_and_linkedlist/array.md index e0abe19be..a19369d84 100755 --- a/docs/chapter_array_and_linkedlist/array.md +++ b/docs/chapter_array_and_linkedlist/array.md @@ -14,7 +14,7 @@ comments: true 观察上图,我们发现 **数组首元素的索引为 $0$** 。你可能会想,这并不符合日常习惯,首个元素的索引为什么不是 $1$ 呢,这不是更加自然吗?我认同你的想法,但请先记住这个设定,后面讲内存地址计算时,我会尝试解答这个问题。 -**数组有多种初始化写法**。根据实际需要,选代码最短的那一种就好。 +**数组初始化**。一般会用到无初始值、给定初始值两种写法,可根据需求选取。在不给定初始值的情况下,一般所有元素会被初始化为默认值 $0$ 。 === "Java" @@ -28,8 +28,12 @@ comments: true ```cpp title="array.cpp" /* 初始化数组 */ - int* arr = new int[5]; - int* nums = new int[5] { 1, 3, 2, 5, 4 }; + // 存储在栈上 + int arr[5]; + int nums[5] { 1, 3, 2, 5, 4 }; + // 存储在堆上 + int* arr1 = new int[5]; + int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; ``` === "Python" diff --git a/docs/chapter_graph/graph.md b/docs/chapter_graph/graph.md index 5f8d861e5..1de9f230d 100644 --- a/docs/chapter_graph/graph.md +++ b/docs/chapter_graph/graph.md @@ -22,15 +22,15 @@ $$ 根据边是否有方向,分为「无向图 Undirected Graph」和「有向图 Directed Graph」。 -- 在无向图中,边表示两结点之间“双向”的连接关系,例如微信或 QQ 中的“好友关系”; +- 在无向图中,边表示两顶点之间“双向”的连接关系,例如微信或 QQ 中的“好友关系”; - 在有向图中,边是有方向的,即 $A \rightarrow B$ 和 $A \leftarrow B$ 两个方向的边是相互独立的,例如微博或抖音上的“关注”与“被关注”关系; ![directed_graph](graph.assets/directed_graph.png) 根据所有顶点是否连通,分为「连通图 Connected Graph」和「非连通图 Disconnected Graph」。 -- 对于连通图,从某个结点出发,可以到达其余任意结点; -- 对于非连通图,从某个结点出发,至少有一个结点无法到达; +- 对于连通图,从某个顶点出发,可以到达其余任意顶点; +- 对于非连通图,从某个顶点出发,至少有一个顶点无法到达; ![connected_graph](graph.assets/connected_graph.png) @@ -52,6 +52,8 @@ $$ 设图的顶点数量为 $n$ ,「邻接矩阵 Adjacency Matrix」使用一个 $n \times n$ 大小的矩阵来表示图,每一行(列)代表一个顶点,矩阵元素代表边,使用 $1$ 或 $0$ 来表示两个顶点之间有边或无边。 +如下图所示,记邻接矩阵为 $M$ 、顶点列表为 $V$ ,则矩阵元素 $M[i][j] = 1$ 代表着顶点 $V[i]$ 到顶点 $V[j]$ 之间有边,相反地 $M[i][j] = 0$ 代表两顶点之间无边。 + ![adjacency_matrix](graph.assets/adjacency_matrix.png) 邻接矩阵具有以下性质: diff --git a/docs/chapter_graph/graph_operations.md b/docs/chapter_graph/graph_operations.md index a9f0c5c02..0042a32d9 100644 --- a/docs/chapter_graph/graph_operations.md +++ b/docs/chapter_graph/graph_operations.md @@ -89,7 +89,7 @@ comments: true === "Zig" ```zig title="graph_adjacency_matrix.zig" - + ``` ## 9.2.2. 基于邻接表的实现 @@ -119,6 +119,12 @@ comments: true 基于邻接表实现图的代码如下所示。 +!!! question "为什么需要使用顶点类 `Vertex` ?" + + 如果我们直接通过顶点值来区分不同顶点,那么值重复的顶点将无法被区分。 + 如果建立一个顶点列表,用索引来区分不同顶点,那么假设我们想要删除索引为 `i` 的顶点,则需要遍历整个邻接表,将其中 $> i$ 的索引全部执行 $-1$ ,这样的操作是比较耗时的。 + 因此,通过引入顶点类 `Vertex` ,每个顶点都是唯一的对象,这样在删除操作时就无需改动其余顶点了。 + === "Java" ```java title="graph_adjacency_list.java" diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs.png new file mode 100644 index 000000000..da53cbaad Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step1.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step1.png new file mode 100644 index 000000000..4e5dea867 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step1.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step10.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step10.png new file mode 100644 index 000000000..d3f279d1e Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step10.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step11.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step11.png new file mode 100644 index 000000000..23959daf6 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step11.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step2.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step2.png new file mode 100644 index 000000000..71ac1e04c Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step2.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step3.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step3.png new file mode 100644 index 000000000..3afd84f85 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step3.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step4.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step4.png new file mode 100644 index 000000000..afa0371e7 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step4.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step5.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step5.png new file mode 100644 index 000000000..98865caad Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step5.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step6.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step6.png new file mode 100644 index 000000000..0555262c2 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step6.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step7.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step7.png new file mode 100644 index 000000000..1f64081ce Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step7.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step8.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step8.png new file mode 100644 index 000000000..30bd78d28 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step8.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_bfs_step9.png b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step9.png new file mode 100644 index 000000000..7ecaa2435 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_bfs_step9.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs.png new file mode 100644 index 000000000..2116a55ef Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step1.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step1.png new file mode 100644 index 000000000..ffe48e3c5 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step1.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step10.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step10.png new file mode 100644 index 000000000..c3d426b9c Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step10.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step11.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step11.png new file mode 100644 index 000000000..57def7b38 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step11.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step2.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step2.png new file mode 100644 index 000000000..813dbe547 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step2.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step3.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step3.png new file mode 100644 index 000000000..a26fad478 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step3.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step4.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step4.png new file mode 100644 index 000000000..71135b062 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step4.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step5.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step5.png new file mode 100644 index 000000000..3b7174a82 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step5.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step6.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step6.png new file mode 100644 index 000000000..0beeca547 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step6.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step7.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step7.png new file mode 100644 index 000000000..9d2649fba Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step7.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step8.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step8.png new file mode 100644 index 000000000..75347b764 Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step8.png differ diff --git a/docs/chapter_graph/graph_traversal.assets/graph_dfs_step9.png b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step9.png new file mode 100644 index 000000000..bf84f8c7a Binary files /dev/null and b/docs/chapter_graph/graph_traversal.assets/graph_dfs_step9.png differ diff --git a/docs/chapter_graph/graph_traversal.md b/docs/chapter_graph/graph_traversal.md new file mode 100644 index 000000000..fba7bb3e9 --- /dev/null +++ b/docs/chapter_graph/graph_traversal.md @@ -0,0 +1,258 @@ +--- +comments: true +--- + +# 9.3. 图的遍历 + +!!! note "图与树的关系" + + 树代表的是“一对多”的关系,而图则自由度更高,可以代表任意“多对多”关系。本质上,**可以把树看作是图的一类特例**。那么显然,树遍历操作也是图遍历操作的一个特例,两者的方法是非常类似的,建议你在学习本章节的过程中将两者融会贯通。 + +「图」与「树」都是非线性数据结构,都需要使用「搜索算法」来实现遍历操作。 + +类似地,图的遍历方式也分为两种,即「广度优先遍历 Breadth-First Traversal」和「深度优先遍历 Depth-First Travsersal」,也称「广度优先搜索 Breadth-First Search」和「深度优先搜索 Depth-First Search」,简称为 BFS 和 DFS 。 + +## 9.3.1. 广度优先遍历 + +**广度优先遍历优是一种由近及远的遍历方式,从距离最近的顶点开始访问,并一层层向外扩张**。具体地,从某个顶点出发,先遍历该顶点的所有邻接顶点,随后遍历下个顶点的所有邻接顶点,以此类推…… + +![graph_bfs](graph_traversal.assets/graph_bfs.png) + +### 算法实现 + +BFS 常借助「队列」来实现。队列具有“先入先出”的性质,这与 BFS “由近及远”的思想是异曲同工的。 + +1. 将遍历起始顶点 `startVet` 加入队列,并开启循环; +2. 在循环的每轮迭代中,弹出队首顶点弹出并记录访问,并将该顶点的所有邻接顶点加入到队列尾部; +3. 循环 `2.` ,直到所有顶点访问完成后结束。 + +为了防止重复遍历顶点,我们需要借助一个哈希表 `visited` 来记录哪些结点已被访问。 + +=== "Java" + + ```java title="graph_bfs.java" + [class]{graph_bfs}-[func]{graphBFS} + ``` + +=== "C++" + + ```cpp title="graph_bfs.cpp" + + ``` + +=== "Python" + + ```python title="graph_bfs.py" + + ``` + +=== "Go" + + ```go title="graph_bfs.go" + + ``` + +=== "JavaScript" + + ```javascript title="graph_bfs.js" + + ``` + +=== "TypeScript" + + ```typescript title="graph_bfs.ts" + + ``` + +=== "C" + + ```c title="graph_bfs.c" + + ``` + +=== "C#" + + ```csharp title="graph_bfs.cs" + + ``` + +=== "Swift" + + ```swift title="graph_bfs.swift" + + ``` + +=== "Zig" + + ```zig title="graph_bfs.zig" + + ``` + +代码相对抽象,建议对照以下动画图示来加深理解。 + +=== "Step 1" + ![graph_bfs_step1](graph_traversal.assets/graph_bfs_step1.png) + +=== "Step 2" + ![graph_bfs_step2](graph_traversal.assets/graph_bfs_step2.png) + +=== "Step 3" + ![graph_bfs_step3](graph_traversal.assets/graph_bfs_step3.png) + +=== "Step 4" + ![graph_bfs_step4](graph_traversal.assets/graph_bfs_step4.png) + +=== "Step 5" + ![graph_bfs_step5](graph_traversal.assets/graph_bfs_step5.png) + +=== "Step 6" + ![graph_bfs_step6](graph_traversal.assets/graph_bfs_step6.png) + +=== "Step 7" + ![graph_bfs_step7](graph_traversal.assets/graph_bfs_step7.png) + +=== "Step 8" + ![graph_bfs_step8](graph_traversal.assets/graph_bfs_step8.png) + +=== "Step 9" + ![graph_bfs_step9](graph_traversal.assets/graph_bfs_step9.png) + +=== "Step 10" + ![graph_bfs_step10](graph_traversal.assets/graph_bfs_step10.png) + +=== "Step 11" + ![graph_bfs_step11](graph_traversal.assets/graph_bfs_step11.png) + +!!! question "广度优先遍历的序列是否唯一?" + + 不唯一。广度优先遍历只要求“由近及远”,而相同距离的多个顶点的遍历顺序允许任意被打乱。以上图为例,顶点 $1$ , $3$ 的访问顺序可以交换、顶点 $2$ , $4$ , $6$ 的访问顺序也可以任意交换、以此类推…… + +### 复杂度分析 + +**时间复杂度:** 所有顶点都会入队、出队一次,使用 $O(|V|)$ 时间;在遍历邻接顶点的过程中,由于是无向图,因此所有边都会被访问 $2$ 次,使用 $O(2|E|)$ 时间;总体使用 $O(|V| + |E|)$ 时间。 + +**空间复杂度:** 列表 `res` ,哈希表 `visited` ,队列 `que` 中的顶点数量最多为 $|V|$ ,使用 $O(|V|)$ 空间。 + +## 9.3.2. 深度优先遍历 + +**深度优先遍历是一种优先走到底、无路可走再回头的遍历方式**。具体地,从某个顶点出发,不断地访问当前结点的某个邻接顶点,直到走到尽头时回溯,再继续走到底 + 回溯,以此类推……直至所有顶点遍历完成时结束。 + +![graph_dfs](graph_traversal.assets/graph_dfs.png) + +### 算法实现 + +这种“走到头 + 回溯”的算法形式一般基于递归来实现。与 BFS 类似,在 DFS 中我们也需要借助一个哈希表 `visited` 来记录已被访问的顶点,以避免重复访问顶点。 + +=== "Java" + + ```java title="graph_dfs.java" + [class]{graph_dfs}-[func]{dfs} + + [class]{graph_dfs}-[func]{graphDFS} + ``` + +=== "C++" + + ```cpp title="graph_dfs.cpp" + + ``` + +=== "Python" + + ```python title="graph_dfs.py" + + ``` + +=== "Go" + + ```go title="graph_dfs.go" + + ``` + +=== "JavaScript" + + ```javascript title="graph_dfs.js" + + ``` + +=== "TypeScript" + + ```typescript title="graph_dfs.ts" + + ``` + +=== "C" + + ```c title="graph_dfs.c" + + ``` + +=== "C#" + + ```csharp title="graph_dfs.cs" + + ``` + +=== "Swift" + + ```swift title="graph_dfs.swift" + + ``` + +=== "Zig" + + ```zig title="graph_dfs.zig" + + ``` + +深度优先遍历的算法流程如下图所示,其中 + +- **直虚线代表向下递推**,代表开启了一个新的递归方法来访问新顶点; +- **曲虚线代表向上回溯**,代表此递归方法已经返回,回溯到了开启此递归方法的位置; + +为了加深理解,请你将图示与代码结合起来,在脑中(或者用笔画下来)模拟整个 DFS 过程,包括每个递归方法何时开启、何时返回。 + +=== "Step 1" + ![graph_dfs_step1](graph_traversal.assets/graph_dfs_step1.png) + +=== "Step 2" + ![graph_dfs_step2](graph_traversal.assets/graph_dfs_step2.png) + +=== "Step 3" + ![graph_dfs_step3](graph_traversal.assets/graph_dfs_step3.png) + +=== "Step 4" + ![graph_dfs_step4](graph_traversal.assets/graph_dfs_step4.png) + +=== "Step 5" + ![graph_dfs_step5](graph_traversal.assets/graph_dfs_step5.png) + +=== "Step 6" + ![graph_dfs_step6](graph_traversal.assets/graph_dfs_step6.png) + +=== "Step 7" + ![graph_dfs_step7](graph_traversal.assets/graph_dfs_step7.png) + +=== "Step 8" + ![graph_dfs_step8](graph_traversal.assets/graph_dfs_step8.png) + +=== "Step 9" + ![graph_dfs_step9](graph_traversal.assets/graph_dfs_step9.png) + +=== "Step 10" + ![graph_dfs_step10](graph_traversal.assets/graph_dfs_step10.png) + +=== "Step 11" + ![graph_dfs_step11](graph_traversal.assets/graph_dfs_step11.png) + +!!! question "深度优先遍历的序列是否唯一?" + + 与广度优先遍历类似,深度优先遍历序列的顺序也不是唯一的。给定某顶点,先往哪个方向探索都行,都是深度优先遍历。 + + 以树的遍历为例,“根 $\rightarrow$ 左 $\rightarrow$ 右”、“左 $\rightarrow$ 根 $\rightarrow$ 右”、“左 $\rightarrow$ 右 $\rightarrow$ 根”分别对应前序、中序、后序遍历,体现三种不同的遍历优先级,而三者都属于深度优先遍历。 + +### 复杂度分析 + +**时间复杂度:** 所有顶点都被访问一次;所有边都被访问了 $2$ 次,使用 $O(2|E|)$ 时间;总体使用 $O(|V| + |E|)$ 时间。 + +**空间复杂度:** 列表 `res` ,哈希表 `visited` 顶点数量最多为 $|V|$ ,递归深度最大为 $|V|$ ,因此使用 $O(|V|)$ 空间。 diff --git a/docs/chapter_tree/binary_tree_traversal.md b/docs/chapter_tree/binary_tree_traversal.md index 04b641d00..f770d70f0 100755 --- a/docs/chapter_tree/binary_tree_traversal.md +++ b/docs/chapter_tree/binary_tree_traversal.md @@ -4,11 +4,13 @@ comments: true # 7.2. 二叉树遍历 -非线性数据结构的遍历操作比线性数据结构更加复杂,往往需要使用搜索算法来实现。常见的二叉树遍历方式有层序遍历、前序遍历、中序遍历、后序遍历。 +从物理结构角度看,树是一种基于链表的数据结构,因此遍历方式也是通过指针(即引用)逐个遍历结点。同时,树还是一种非线性数据结构,这导致遍历树比遍历链表更加复杂,需要使用搜索算法来实现。 + +常见的二叉树遍历方式有层序遍历、前序遍历、中序遍历、后序遍历。 ## 7.2.1. 层序遍历 -「层序遍历 Hierarchical-Order Traversal」从顶至底、一层一层地遍历二叉树,并在每层中按照从左到右的顺序访问结点。 +「层序遍历 Level-Order Traversal」从顶至底、一层一层地遍历二叉树,并在每层中按照从左到右的顺序访问结点。 层序遍历本质上是「广度优先搜索 Breadth-First Traversal」,其体现着一种“一圈一圈向外”的层进遍历方式。 @@ -16,68 +18,76 @@ comments: true

Fig. 二叉树的层序遍历

+### 实现代码 + 广度优先遍历一般借助「队列」来实现。队列的规则是“先进先出”,广度优先遍历的规则是 ”一层层平推“ ,两者背后的思想是一致的。 === "Java" ```java title="binary_tree_bfs.java" - [class]{binary_tree_bfs}-[func]{hierOrder} + [class]{binary_tree_bfs}-[func]{levelOrder} ``` === "C++" ```cpp title="binary_tree_bfs.cpp" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "Python" ```python title="binary_tree_bfs.py" - [class]{}-[func]{hier_order} + [class]{}-[func]{level_order} ``` === "Go" ```go title="binary_tree_bfs.go" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "JavaScript" ```javascript title="binary_tree_bfs.js" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "TypeScript" ```typescript title="binary_tree_bfs.ts" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "C" ```c title="binary_tree_bfs.c" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "C#" ```csharp title="binary_tree_bfs.cs" - [class]{binary_tree_bfs}-[func]{hierOrder} + [class]{binary_tree_bfs}-[func]{levelOrder} ``` === "Swift" ```swift title="binary_tree_bfs.swift" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` === "Zig" ```zig title="binary_tree_bfs.zig" - [class]{}-[func]{hierOrder} + [class]{}-[func]{levelOrder} ``` +### 复杂度分析 + +**时间复杂度**:所有结点被访问一次,使用 $O(n)$ 时间,其中 $n$ 为结点数量。 + +**空间复杂度**:当为满二叉树时达到最差情况,遍历到最底层前,队列中最多同时存在 $\frac{n + 1}{2}$ 个结点,使用 $O(n)$ 空间。 + ## 7.2.2. 前序、中序、后序遍历 相对地,前、中、后序遍历皆属于「深度优先遍历 Depth-First Traversal」,其体现着一种“先走到尽头,再回头继续”的回溯遍历方式。 @@ -98,6 +108,8 @@ comments: true +### 实现代码 + === "Java" ```java title="binary_tree_dfs.java" @@ -201,3 +213,9 @@ comments: true !!! note 使用循环一样可以实现前、中、后序遍历,但代码相对繁琐,有兴趣的同学可以自行实现。 + +### 复杂度分析 + +**时间复杂度**:所有结点被访问一次,使用 $O(n)$ 时间,其中 $n$ 为结点数量。 + +**空间复杂度**:当树退化为链表时达到最差情况,递归深度达到 $n$ ,系统使用 $O(n)$ 栈帧空间。 diff --git a/mkdocs.yml b/mkdocs.yml index d52f01d37..aa57e0942 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -166,7 +166,8 @@ nav: - 8.1. 堆(Heap): chapter_heap/heap.md - 9. 图: - 9.1. 图(Graph): chapter_graph/graph.md - - 9.2. 图基础操作: chapter_graph/graph_operations.md + - 9.2. 图基础操作: chapter_graph/graph_operations.md + - 9.3. 图的遍历: chapter_graph/graph_traversal.md - 10. 查找算法: - 10.1. 线性查找: chapter_searching/linear_search.md - 10.2. 二分查找: chapter_searching/binary_search.md