[AlgoExpert] Topological Sort

Topological Sort

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <vector>
using namespace std;

vector<int> topologicalSort(vector<int> jobs, vector<vector<int>> deps) {
unordered_map<int, vector<int>> adj;
unordered_map<int, int> ind;
vector<int> res;
queue<int> q;
for(auto& dep : deps) {
int u = dep[0], v = dep[1];
ind[v]++;
adj[u].push_back(v);
}

for(auto& job : jobs) {
if(ind[job] == 0)
q.push(job);
}

while(!q.empty()) {
auto u = q.front(); q.pop();
res.push_back(u);
for(auto& v : adj[u]) {
if(--ind[v] == 0)
q.push(v);
}
}
if(res.size() == jobs.size())
return res;
return {};
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/11/PS/AlgoExpert/topological-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.