上一篇的文章是用DFS解决的,但如果遇到大规模图的时候会容易引起栈溢出,所以采用不涉及递归的BFS是个不错的选择。
#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]; //标记是否被加入
int inque[MAX]; //入度
queue<DirectedGraphNode*> temp; //辅助用的队列
vector<DirectedGraphNode*> result;
void bfs(DirectedGraphNode* r) //广度优先搜索法,参数r是入度为0的结点
{
DirectedGraphNode* s;
temp.push(r);
Visited[r->label]=true;
while(!temp.empty())
{
s=temp.front(); temp.pop();
result.push_back(s); //将入度为0的点的label加入vector
//遍历邻居
for(int i=0;i<s->neighbors.size();i++)
{
inque[s->neighbors[i]->label]--;
if(inque[s->neighbors[i]->label]==0&&Visited[s->neighbors[i]->label]==false)
{
Visited[s->neighbors[i]->label]=true;
temp.push(s->neighbors[i]);
}
}
}
}
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
for(int i=0;i<graph.size();i++) //初始化数据
{
inque[graph[i]->label]=0;
Visited[graph[i]->label]=false;
}
for(int i=0;i<graph.size();i++) //统计每个节点的入度
for(int j=0;j<graph[i]->neighbors.size();j++)
inque[graph[i]->neighbors[j]->label]++;
for(int i=0;i<graph.size();i++)
{
if(inque[graph[i]->label]==0&&Visited[graph[i]->label]==false)
bfs(graph[i]);
}
return result;
}
};