cpp-algo-cases/chapter_graph/graph_dfs.cpp

56 lines
1.5 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: graph_dfs.cpp
* Created Time: 2023-03-02
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
#include "./graph_adjacency_list.cpp"
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȱ<EFBFBD><C8B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void dfs(GraphAdjList &graph, unordered_set<Vertex *> &visited, vector<Vertex *> &res, Vertex *vet) {
res.push_back(vet); // <20><>¼<EFBFBD><C2BC><EFBFBD>ʶ<EFBFBD><CAB6><EFBFBD>
visited.emplace(vet); // <20><><EFBFBD>Ǹö<C7B8><C3B6><EFBFBD><EFBFBD>ѱ<EFBFBD><D1B1><EFBFBD><EFBFBD><EFBFBD>
// <20><><EFBFBD><EFBFBD><EFBFBD>ö<EFBFBD><C3B6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڽӶ<DABD><D3B6><EFBFBD>
for (Vertex *adjVet : graph.adjList[vet]) {
if (visited.count(adjVet))
continue; // <20><><EFBFBD><EFBFBD><EFBFBD>ѱ<EFBFBD><D1B1><EFBFBD><EFBFBD>ʵĶ<CAB5><C4B6><EFBFBD>
// <20>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڽӶ<DABD><D3B6><EFBFBD>
dfs(graph, visited, res, adjVet);
}
}
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȱ<EFBFBD><C8B1><EFBFBD> */
// ʹ<><CAB9><EFBFBD>ڽӱ<DABD><D3B1><EFBFBD><EFBFBD><EFBFBD>ʾͼ<CABE><CDBC><EFBFBD>Ա<EFBFBD><D4B1><EFBFBD>ȡָ<C8A1><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڽӶ<DABD><D3B6><EFBFBD>
vector<Vertex *> graphDFS(GraphAdjList &graph, Vertex *startVet) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
vector<Vertex *> res;
// <20><>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڼ<EFBFBD>¼<EFBFBD>ѱ<EFBFBD><D1B1><EFBFBD><EFBFBD>ʹ<EFBFBD><CAB9>Ķ<EFBFBD><C4B6><EFBFBD>
unordered_set<Vertex *> visited;
dfs(graph, visited, res, startVet);
return res;
}
/* Driver Code */
int main() {
/* <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͼ */
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]}};
GraphAdjList graph(edges);
cout << "\n<EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͼΪ" << endl;
graph.print();
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȱ<EFBFBD><C8B1><EFBFBD> */
vector<Vertex *> res = graphDFS(graph, v[0]);
cout << "\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȱ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>DFS<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ" << endl;
printVector(vetsToVals(res));
// <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
for (Vertex *vet : v) {
delete vet;
}
return 0;
}