Topological Sorting
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.
Note
You can assume that there is at least one topological order in the graph.
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
or
[0, 2, 3, 1, 5, 4]
or
....
---------------------- thinking ------------------------------
https://hellosmallworld123.wordpress.com/2014/04/17/topological-sort/
http://www.cnblogs.com/lishiblog/p/4187867.html
---------------------- codes ---------------------------------
/**
* 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*> result;
vector<DirectedGraphNode*>roots = findRoot(graph);
stack<DirectedGraphNode*> stack;
unordered_set<DirectedGraphNode*> visited;
for (int i = 0; i < roots.size(); i++) {
stack.push(roots[i]);
visited.insert(roots[i]);
}
while (!stack.empty()) {
DirectedGraphNode* cur = stack.top();
bool all_visited = true;
for (int i = 0; i < cur->neighbors.size(); i++) {
if (visited.find(cur->neighbors[i]) == visited.end()) {
all_visited = false;
visited.insert(cur->neighbors[i]);
stack.push(cur->neighbors[i]);
//bug here : only push one child at a time
break;
}
}
if (all_visited) {
result.insert(result.begin(), cur);
stack.pop();
}
}
return result;
}
//bug here: a DAG might have multiple root nodes to start
vector<DirectedGraphNode*> findRoot(vector<DirectedGraphNode*> &graph) {
unordered_set<DirectedGraphNode*> set;
for (int i = 0; i < graph.size(); i++) {
for (int k = 0; k < graph[i]->neighbors.size(); k++) {
if (set.find(graph[i]->neighbors[k]) == set.end()) {
set.insert(graph[i]->neighbors[k]);
}
}
}
vector<DirectedGraphNode*> result;
for (int i = 0; i < graph.size(); i++) {
if (set.find(graph[i]) == set.end()) {
result.push_back(graph[i]);
}
}
return result;
}
};
No comments:
Post a Comment