2023-03-08 19:16:46 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: graph_bfs.cs
|
|
|
|
|
* Created Time: 2023-03-08
|
|
|
|
|
* Author: hpstory (hpstory1024@163.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-04-14 05:57:07 +08:00
|
|
|
|
namespace hello_algo.chapter_graph;
|
|
|
|
|
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public class graph_bfs {
|
2023-12-28 18:06:09 +08:00
|
|
|
|
/* 广度优先遍历 */
|
2023-04-14 05:57:07 +08:00
|
|
|
|
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
|
2023-11-26 23:18:44 +08:00
|
|
|
|
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
|
2023-04-14 05:57:07 +08:00
|
|
|
|
// 顶点遍历序列
|
2023-11-26 23:18:44 +08:00
|
|
|
|
List<Vertex> res = [];
|
2024-04-28 22:00:25 +08:00
|
|
|
|
// 哈希集合,用于记录已被访问过的顶点
|
2023-11-26 23:18:44 +08:00
|
|
|
|
HashSet<Vertex> visited = [startVet];
|
2023-04-14 05:57:07 +08:00
|
|
|
|
// 队列用于实现 BFS
|
2023-10-08 01:33:46 +08:00
|
|
|
|
Queue<Vertex> que = new();
|
2023-04-14 05:57:07 +08:00
|
|
|
|
que.Enqueue(startVet);
|
|
|
|
|
// 以顶点 vet 为起点,循环直至访问完所有顶点
|
2023-04-23 03:03:12 +08:00
|
|
|
|
while (que.Count > 0) {
|
2023-04-14 05:57:07 +08:00
|
|
|
|
Vertex vet = que.Dequeue(); // 队首顶点出队
|
|
|
|
|
res.Add(vet); // 记录访问顶点
|
2023-04-23 03:03:12 +08:00
|
|
|
|
foreach (Vertex adjVet in graph.adjList[vet]) {
|
|
|
|
|
if (visited.Contains(adjVet)) {
|
2023-12-02 06:21:34 +08:00
|
|
|
|
continue; // 跳过已被访问的顶点
|
2023-03-08 19:16:46 +08:00
|
|
|
|
}
|
2023-04-14 05:57:07 +08:00
|
|
|
|
que.Enqueue(adjVet); // 只入队未访问的顶点
|
|
|
|
|
visited.Add(adjVet); // 标记该顶点已被访问
|
2023-03-08 19:16:46 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-14 05:57:07 +08:00
|
|
|
|
// 返回顶点遍历序列
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Test]
|
2023-04-23 03:03:12 +08:00
|
|
|
|
public void Test() {
|
2023-04-14 05:57:07 +08:00
|
|
|
|
/* 初始化无向图 */
|
2023-11-26 23:18:44 +08:00
|
|
|
|
Vertex[] v = Vertex.ValsToVets([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]]
|
|
|
|
|
];
|
2023-03-08 19:16:46 +08:00
|
|
|
|
|
2023-10-08 01:33:46 +08:00
|
|
|
|
GraphAdjList graph = new(edges);
|
2023-04-14 05:57:07 +08:00
|
|
|
|
Console.WriteLine("\n初始化后,图为");
|
2023-10-08 01:33:46 +08:00
|
|
|
|
graph.Print();
|
2023-03-08 19:16:46 +08:00
|
|
|
|
|
2023-12-28 18:06:09 +08:00
|
|
|
|
/* 广度优先遍历 */
|
2023-10-08 01:33:46 +08:00
|
|
|
|
List<Vertex> res = GraphBFS(graph, v[0]);
|
2023-04-14 05:57:07 +08:00
|
|
|
|
Console.WriteLine("\n广度优先遍历(BFS)顶点序列为");
|
2023-04-21 14:59:22 +08:00
|
|
|
|
Console.WriteLine(string.Join(" ", Vertex.VetsToVals(res)));
|
2023-03-08 19:16:46 +08:00
|
|
|
|
}
|
2023-04-23 03:03:12 +08:00
|
|
|
|
}
|