Last active
March 6, 2018 05:43
-
-
Save maxkibble/16da36afa5c6d21b88da546d741c84f5 to your computer and use it in GitHub Desktop.
topological sort for directed graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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