way:找入度为0的节点删除,减少其他节点的入度,继续找入度为0的节点,直到删除完所有的图节点。(遍历node的neighbors就能得到neighbors的入度信息)
cpp
#include<iostream>
#include<vector>
#include<map>
#include<queue>
using namespace std;
class Node {
public:
int label;
vector<Node*> neighbors;
Node(int x)
{
label=x;
}
};
vector<Node*> topSort(vector<Node*> graph)
{
map<Node*, int>indegreeMap;
//统计所有节点的入度信息到indegreeMap中
for(auto node: graph)
{
indegreeMap[node]=0;
}
for(auto node: graph)
{
for(auto next: node->neighbors)
{
indegreeMap[next] = indegreeMap[next]+1;
}
}
//将入度为0的节点放入zeroQue中
queue<Node*> zeroQue;
for(auto pa: indegreeMap)
{
if(pa.second == 0)
{
zeroQue.push(pa.first);
}
}
vector<Node*> result;
//开始删除节点,减少入度
while(!zeroQue.empty())
{
Node *cur = zeroQue.front();
zeroQue.pop();
result.push_back(cur);
for(auto next: cur->neighbors)
{
indegreeMap[next] = indegreeMap[next]-1;
if(indegreeMap[next]==0)
{
zeroQue.push(next);
}
}
}
return result;
}