2023-03-02 18:57:33 +08:00
|
|
|
|
/**
|
|
|
|
|
* File: graph_dfs.cpp
|
|
|
|
|
* Created Time: 2023-03-02
|
|
|
|
|
* Author: Krahets (krahets@163.com)
|
|
|
|
|
*/
|
|
|
|
|
|
2023-04-24 04:11:18 +08:00
|
|
|
|
#include "../utils/common.hpp"
|
2023-03-02 18:57:33 +08:00
|
|
|
|
#include "./graph_adjacency_list.cpp"
|
|
|
|
|
|
|
|
|
|
/* 深度优先遍历 DFS 辅助函数 */
|
2023-04-14 03:44:02 +08:00
|
|
|
|
void dfs(GraphAdjList &graph, unordered_set<Vertex *> &visited, vector<Vertex *> &res, Vertex *vet) {
|
2023-03-02 18:57:33 +08:00
|
|
|
|
res.push_back(vet); // 记录访问顶点
|
|
|
|
|
visited.emplace(vet); // 标记该顶点已被访问
|
|
|
|
|
// 遍历该顶点的所有邻接顶点
|
2023-04-14 03:44:02 +08:00
|
|
|
|
for (Vertex *adjVet : graph.adjList[vet]) {
|
2023-03-02 18:57:33 +08:00
|
|
|
|
if (visited.count(adjVet))
|
2023-12-02 06:21:34 +08:00
|
|
|
|
continue; // 跳过已被访问的顶点
|
2023-03-02 18:57:33 +08:00
|
|
|
|
// 递归访问邻接顶点
|
|
|
|
|
dfs(graph, visited, res, adjVet);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* 深度优先遍历 DFS */
|
|
|
|
|
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
|
2023-04-14 03:44:02 +08:00
|
|
|
|
vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
|
2023-03-02 18:57:33 +08:00
|
|
|
|
// 顶点遍历序列
|
2023-04-14 03:44:02 +08:00
|
|
|
|
vector<Vertex *> res;
|
2023-03-02 18:57:33 +08:00
|
|
|
|
// 哈希表,用于记录已被访问过的顶点
|
2023-04-14 03:44:02 +08:00
|
|
|
|
unordered_set<Vertex *> visited;
|
2023-03-02 18:57:33 +08:00
|
|
|
|
dfs(graph, visited, res, startVet);
|
|
|
|
|
return res;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
|
int main() {
|
|
|
|
|
/* 初始化无向图 */
|
2023-04-14 03:44:02 +08:00
|
|
|
|
vector<Vertex *> v = valsToVets(vector<int>{0, 1, 2, 3, 4, 5, 6});
|
|
|
|
|
vector<vector<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]}};
|
2023-03-02 18:57:33 +08:00
|
|
|
|
GraphAdjList graph(edges);
|
|
|
|
|
cout << "\n初始化后,图为" << endl;
|
|
|
|
|
graph.print();
|
|
|
|
|
|
|
|
|
|
/* 深度优先遍历 DFS */
|
2023-04-14 03:44:02 +08:00
|
|
|
|
vector<Vertex *> res = graphDFS(graph, v[0]);
|
2023-03-02 18:57:33 +08:00
|
|
|
|
cout << "\n深度优先遍历(DFS)顶点序列为" << endl;
|
2023-04-14 03:44:02 +08:00
|
|
|
|
printVector(vetsToVals(res));
|
2023-03-02 18:57:33 +08:00
|
|
|
|
|
|
|
|
|
// 释放内存
|
|
|
|
|
for (Vertex *vet : v) {
|
|
|
|
|
delete vet;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
|
}
|