Topological Sorting
Description
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
Learn more about representation of graphs
Example For graph as follow: The topological order can be: [0, 1, 2, 3, 4, 5] [0, 2, 3, 1, 5, 4]
Link
Method
- x
- x
Example
- 1
/** * 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 if (graph.empty()) { return {}; } vector<DirectedGraphNode*> result; int len = graph.size(); unordered_map<DirectedGraphNode*, int> indegree; // find all nodes with 0 indegree for (int i = 0; i < len; ++i) { // search all neighbors for (auto& neighbor : graph[i]->neighbors) { // cannot find if (indegree.find(neighbor) == indegree.end()) { indegree[neighbor] = 1; } else { // can find indegree[neighbor]++; } } } // init q with indegree 0, namely, indegree cannot find queue<DirectedGraphNode*> q; for (const auto& entry : graph) { if (indegree.find(entry) != indegree.end()) { continue; } q.push(entry); } // bfs while (!q.empty()) { // DirectedGraphNode* cur = q.front(); auto& cur = q.front(); q.pop(); result.push_back(cur); for (const auto& i : cur->neighbors) { indegree[i]--; if (indegree[i] == 0) { q.push(i); } } } return result; } };
Similar problems
x
Tags
x