题目描述:
Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge
A -> B
in graph, A must before B in the order list. - The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.
Notice
You can assume that there is at least one topological order in the graph.
Clarification
Example
题目思路:
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
这题就是。。。topological sorting的算法之一:我用了dfs的code,实现的是链接的算法--topological sorting
Mycode (AC = 162ms):
/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) {
// write your code here
vector<DirectedGraphNode*> ans;
if (graph.size() == 0) return ans;
set<int> visited;
for (int i = 0; i < graph.size(); i++) {
if (visited.find(graph[i]->label) == visited.end()) {
topSort(ans, graph, visited, graph[i]);
}
}
reverse(ans.begin(), ans.end());
return ans;
}
void topSort(vector<DirectedGraphNode*>& ans,
vector<DirectedGraphNode*>& graph,
set<int>& visited,
DirectedGraphNode *node)
{
if (node == NULL || visited.find(node->label) != visited.end()) {
return;
}
visited.insert(node->label);
for (int i = 0; i < node->neighbors.size(); i++) {
topSort(ans, graph, visited, node->neighbors[i]);
}
ans.push_back(node);
}
};