给定一个有向图,图节点的拓扑排序被定义为:
- 对于每条有向边A--> B,则A必须排在B之前
- 拓扑排序的第一个节点可以是任何在图中没有其他节点指向它的节点
找到给定图的任一拓扑排序
注意事项
你可以假设图中至少存在一种拓扑排序
样例
对于下列图:
这个图的拓扑排序可能是:
[0, 1, 2, 3, 4, 5]
或者
[0, 2, 3, 1, 5, 4]
或者
....
下面用递归思想和深度优先搜索实现拓扑排序的算法。
#include <algorithm>
using namespace std;
/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
const int MAX=99999;
class Solution {
public:
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
bool Visited[MAX]; //标记是否被访问过
vector<DirectedGraphNode*> result;
void dfs(DirectedGraphNode* r)
{
Visited[r->label]=true; //标记已经访问过
for(int i=0;i<r->neighbors.size();i++) //遍历所有的邻居
{
if(!Visited[r->neighbors[i]->label]) //如果邻居没有被访问过,则深入访问
dfs(r->neighbors[i]);
}
result.push_back(r); //将访问结束的顶点添加到vecotr
}
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
for(int i=0;i<graph.size();i++)
if(!Visited[graph[i]->label])
dfs(graph[i]);
reverse(result.begin(),result.end()); //记得逆向
return result;
}
};