Topological Sorting
- Lintcode : 127 / Leetcode :
- Level : Medium
Problem
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.
Example
For graph as follow:
图片
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Challenge
Can you do it in both BFS and DFS?
Clarification
Learn more about representation of graphs
Notice
You can assume that there is at least one topological order in the graph.
Concept & Algorithm
Time Complexity & Space Complexity
time : O(v edges)
space: O(v edges)
Answer
/**
* Definition for Directed graph.
* struct DirectedGraphNode {
* int label;
* vector<DirectedGraphNode *> neighbors;
* DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*>& graph) {
unordered_map<DirectedGraphNode*, set<DirectedGraphNode*>> edges;
unordered_map<DirectedGraphNode*, int> degree;
for (auto g : graph) {
degree[g];
for (int i = 0; i < g -> neighbors.size(); i++) {
edges[g].insert(g -> neighbors[i]);
degree[g -> neighbors[i]]++;
}
}
queue<DirectedGraphNode*> q;
vector<DirectedGraphNode*> ans;
for (auto it = degree.begin(); it != degree.end(); it++) {
if (it -> second == 0) q.push(it -> first);
}
while (!q.empty()) {
DirectedGraphNode* n = q.front(); q.pop();
ans.push_back(n);
for (auto it = edges[n].begin(); it != edges[n].end(); it++) {
degree[*it]--;
if (degree[*it] == 0) q.push(*it);
}
}
return ans;
}
};
沒有留言:
張貼留言