Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Apply Kahn's algorithm to obtain a topological sorting of the original graph. */
- vector<int> topologicalSort(vector<vector<tuple<int,int,int>>> graph)
- {
- queue<int> Z;
- vector<int> topological_sort;
- int visited_nodes = 0;
- vector<int> indegree = getIndegree(graph);
- for (int i = 0; i < graph.size(); i++)
- {
- tuple<int,int,int> tuple = graph[i][0];
- if(indegree[i] == 0)
- Z.push(get<0>(tuple) - 1);
- }
- while (!Z.empty())
- {
- int vertex = Z.front();
- //cout << vertex;
- Z.pop();
- topological_sort.push_back(vertex);
- for (int i = 1; i < graph[vertex].size(); i++)
- {
- tuple<int,int,int> tuple = graph[vertex][i];
- int idx = get<0>(tuple) - 1;
- indegree[idx] -= 1;
- if(indegree[idx] == 0)
- {
- Z.push(idx);
- }
- }
- visited_nodes++;
- }
- if(visited_nodes != graph.size())
- {
- cout << "There is a cycle!" << endl;
- //return vector<int>(0);
- }
- return topological_sort;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement