-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathKahnsAlgorithm.js
More file actions
48 lines (41 loc) · 995 Bytes
/
KahnsAlgorithm.js
File metadata and controls
48 lines (41 loc) · 995 Bytes
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Kahn's Algorithm for Topological Sort
function kahnTopologicalSort(vertices, edges) {
const adj = new Map()
const indegree = new Array(vertices).fill(0)
// Build adjacency list & indegree count
for (let [u, v] of edges) {
if (!adj.has(u)) adj.set(u, [])
adj.get(u).push(v)
indegree[v]++
}
const queue = []
for (let i = 0; i < vertices; i++) {
if (indegree[i] === 0) queue.push(i)
}
const topo = []
while (queue.length > 0) {
const node = queue.shift()
topo.push(node)
if (adj.has(node)) {
for (let neigh of adj.get(node)) {
indegree[neigh]--
if (indegree[neigh] === 0) queue.push(neigh)
}
}
}
if (topo.length !== vertices) {
throw new Error('Graph has a cycle, topological sort not possible')
}
return topo
}
// Example usage
const vertices = 6
const edges = [
[5, 2],
[5, 0],
[4, 0],
[4, 1],
[2, 3],
[3, 1]
]
console.log('Topological Sort:', kahnTopologicalSort(vertices, edges))