graphs topological sort code example
Example 1: topological sorting
int n;
vector<vector<int>> adj;
vector<bool> visited;
vector<int> ans;
void dfs(int v) {
visited[v] = true;
for (int u : adj[v]) {
if (!visited[u])
dfs(u);
}
ans.push_back(v);
}
void topological_sort() {
visited.assign(n, false);
ans.clear();
for (int i = 0; i < n; ++i) {
if (!visited[i])
dfs(i);
}
reverse(ans.begin(), ans.end());
}
Example 2: topological sort
void dfs_helper(T src, map<int,bool>& visited, list<T> &ordering) {
visited[src] = true;
for(T nbr:l[src]) {
if(!visited[nbr]) {
dfs_helper(src,visited,ordering);
}
}
ordering.push_front(src);
}
int dfs(T src) {
map<int,bool> visited;
list<T> ordering;
for(auto p:l) {
T node = p.first;
visited[node] = false;
}
for(auto p:l) {
T node = p.first;
if(!visited[node]) {
dfs_helper(node,visited,ordering);
}
}
for(auto node:ordering) {
cout << node << endl;
}
}