순서가 정해져있는 작업을 차례로 수행해야 할 때 그 순서를 결정해주기 위한 알고리즘
순서가 있으므로 사이클이 존재하지 않는 방향 그래프(DAG, directed acyclic graph)로 구성할 수 있을 때 사용 가능하다.
모든 노드를 순회하면서 각 노드의 간선을 순차적으로 제거하기 때문에 노드의 수를 V, 간선의 수를 E라 할때 O(V+E)
의 시간복잡도를 보인다.
JavaScript로는 아래와 같이 구현할 수 있다.
function topologySort(n, m, node) {
const answer = [];
const graph = Array.from(Array(n + 1), () => Array().fill(0));
const indegrees = Array(n + 1).fill(0);
const queue = [];
for (let [a, b] of node) {
graph[a].push(b);
indegrees[b]++;
}
for (let i = 1; i < n + 1; i++) {
if (indegrees[i] === 0) queue.push(i);
}
while (queue.length) {
const el= queue.shift();
answer.push(el);
for (let next of graph[el]) {
indegrees[next]--;
if (indegrees[next] === 0) queue.push(next);
}
}
return answer;
}