赞
踩
拓扑排序的深度优先算法(Topological Sort with Depth-First Search)是一种在有向无环图(DAG)中进行排序的方法。
。该算法使用递归来进行深度优先搜索,并在搜索完成后将节点添加到排序结果中。
#include <iostream> #include <vector> #include <stack> using namespace std; class Graph { private: int numVertices; // 图中节点的数量 vector<vector<int>> adjacencyList; // 邻接表 public: Graph(int vertices) : numVertices(vertices) { adjacencyList.resize(vertices); } // 添加有向边 void addEdge(int start, int end) { adjacencyList[start].push_back(end); } // 深度优先搜索拓扑排序算法 void topologicalSortDFS(int vertex, vector<bool>& visited, stack<int>& result) { visited[vertex] = true; // 递归访问相邻节点 for (int neighbor : adjacencyList[vertex]) { if (!visited[neighbor]) { topologicalSortDFS(neighbor, visited, result); } } // 将当前节点压入栈中 result.push(vertex); } // 执行拓扑排序 vector<int> topologicalSort() { vector<bool> visited(numVertices, false); stack<int> result; // 对每个未访问的节点执行深度优先搜索 for (int i = 0; i < numVertices; ++i) { if (!visited[i]) { topologicalSortDFS(i, visited, result); } } // 从栈中提取排序结果 vector<int> sortedResult; while (!result.empty()) { sortedResult.push_back(result.top()); result.pop(); } return sortedResult; } }; int main() { Graph graph(6); graph.addEdge(5, 2); graph.addEdge(5, 0); graph.addEdge(4, 0); graph.addEdge(4, 1); graph.addEdge(2, 3); graph.addEdge(3, 1); vector<int> result = graph.topologicalSort(); cout << "Topological Sort: "; for (int vertex : result) { cout << vertex << " "; } cout << endl; return 0; }
拓扑排序的广度优先算法(Topological Sort with Breadth-First Search)是一种在有向无环图(DAG)中进行排序的方法。与深度优先算法不同,广度优先算法使用队列来实现拓扑排序。
#include <iostream> #include <vector> #include <queue> using namespace std; class Graph { private: int numVertices; // 图中节点的数量 vector<vector<int>> adjacencyList; // 邻接表 public: Graph(int vertices) : numVertices(vertices) { adjacencyList.resize(vertices); } // 添加有向边 void addEdge(int start, int end) { adjacencyList[start].push_back(end); } // 拓扑排序算法 vector<int> topologicalSort() { vector<int> inDegree(numVertices, 0); // 记录每个节点的入度 queue<int> q; // 用于BFS的队列 // 计算每个节点的入度 for (int i = 0; i < numVertices; ++i) { for (int neighbor : adjacencyList[i]) { inDegree[neighbor]++; } } // 将入度为0的节点加入队列 for (int i = 0; i < numVertices; ++i) { if (inDegree[i] == 0) { q.push(i); } } vector<int> result; // 用于存储排序结果 // 执行广度优先搜索 while (!q.empty()) { int current = q.front(); q.pop(); result.push_back(current); // 更新相邻节点的入度,并将入度为0的节点加入队列 for (int neighbor : adjacencyList[current]) { inDegree[neighbor]--; if (inDegree[neighbor] == 0) { q.push(neighbor); } } } return result; } }; int main() { Graph graph(6); graph.addEdge(5, 2); graph.addEdge(5, 0); graph.addEdge(4, 0); graph.addEdge(4, 1); graph.addEdge(2, 3); graph.addEdge(3, 1); vector<int> result = graph.topologicalSort(); cout << "Topological Sort: "; for (int vertex : result) { cout << vertex << " "; } cout << endl; return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。