Skip to content
Snippets Groups Projects
Commit d1279cbe authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add topological_sort

parent c67e7856
No related branches found
No related tags found
No related merge requests found
/**
* Topological Sort
*
* Complexity (Time): O(n + m)
* Complexity (Space): O(n + m)
*/
stack<int> S;
vector<int> graph[MAX];
int cont[MAX];
// Fill stack and check for cycles
bool dfs(int x) {
cont[x] = 1;
for (auto i : graph[x]) {
if (cont[i] == 1)
return true;
if (!cont[i] && dfs(i))
return true;
}
cont[x] = 2;
S.push(x);
return false;
}
// Return topological sort of graph with n vertices
bool topological_sort(int n, vector<int> &tsort) {
memset(cont, 0, sizeof cont);
bool cycle = false;
for (int i = 0; i < n; ++i)
if (!cont[i])
cycle |= dfs(i);
if (cycle)
return true;
while (!S.empty()) {
tsort.push_back(S.top());
S.pop();
}
return false;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment