Skip to content

Instantly share code, notes, and snippets.

@maxkibble
Last active March 6, 2018 05:43
Show Gist options
  • Select an option

  • Save maxkibble/16da36afa5c6d21b88da546d741c84f5 to your computer and use it in GitHub Desktop.

Select an option

Save maxkibble/16da36afa5c6d21b88da546d741c84f5 to your computer and use it in GitHub Desktop.
topological sort for directed graph
using std::vector;
using std::queue;
vector<int> topsort(const vector<vector<int> > &g) {
int n = g.size();
vector<int> d(n);
for(int i = 0; i < n; i++)
for(int j = 0; j < g[i].size(); j++)
d[g[i][j]]++;
queue<int> q;
vector<int> seq;
for(int i = 0; i < n; i++)
if(!d[i]) q.push(i);
while(!q.empty()) {
int hd = q.front();
q.pop();
seq.push_back(hd);
for(int i = 0; i < g[hd].size(); i++) {
int dst = g[hd][i];
d[dst]--;
if(!d[dst]) q.push(dst);
}
}
return seq;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment