Skip to content

Commit 7d025a7

Browse files
committed
[FEATURE]: Add Kahn's Algorithm in Graphs #1795
1 parent 08d8c6b commit 7d025a7

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

Graphs/KahnsAlgorithm.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
export function kahnTopologicalSort(V, edges) {
2+
const adj = Array.from({ length: V }, () => [])
3+
const indegree = new Array(V).fill(0)
4+
5+
for (const [u, v] of edges) {
6+
adj[u].push(v)
7+
indegree[v]++
8+
}
9+
10+
const queue = []
11+
for (let i = 0; i < V; i++) {
12+
if (indegree[i] === 0) queue.push(i)
13+
}
14+
15+
const topoOrder = []
16+
let idx = 0
17+
while (idx < queue.length) {
18+
const node = queue[idx++]
19+
topoOrder.push(node)
20+
21+
for (const nei of adj[node]) {
22+
indegree[nei]--
23+
if (indegree[nei] === 0) queue.push(nei)
24+
}
25+
}
26+
27+
if (topoOrder.length !== V) return []
28+
return topoOrder
29+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { kahnTopologicalSort } from '../KahnsAlgorithm.js'
2+
3+
describe("Kahn's Algorithm - Topological Sort", () => {
4+
test('returns a valid topological order for a DAG', () => {
5+
const V = 6
6+
const edges = [
7+
[5, 2],
8+
[5, 0],
9+
[4, 0],
10+
[4, 1],
11+
[2, 3],
12+
[3, 1]
13+
]
14+
15+
const order = kahnTopologicalSort(V, edges)
16+
expect(order.length).toBe(V)
17+
18+
// verify topological property
19+
const pos = new Array(V)
20+
for (let i = 0; i < order.length; i++) pos[order[i]] = i
21+
22+
for (const [u, v] of edges) {
23+
expect(pos[u]).toBeLessThan(pos[v])
24+
}
25+
})
26+
27+
test('returns empty array when graph contains a cycle', () => {
28+
const V = 3
29+
const edges = [
30+
[0, 1],
31+
[1, 2],
32+
[2, 0] // cycle
33+
]
34+
const order = kahnTopologicalSort(V, edges)
35+
expect(order).toEqual([])
36+
})
37+
38+
test('includes isolated nodes', () => {
39+
const V = 4
40+
const edges = [
41+
[0, 1],
42+
[2, 3]
43+
]
44+
45+
const order = kahnTopologicalSort(V, edges)
46+
expect(order.length).toBe(V)
47+
48+
const pos = new Array(V)
49+
for (let i = 0; i < order.length; i++) pos[order[i]] = i
50+
51+
for (const [u, v] of edges) {
52+
expect(pos[u]).toBeLessThan(pos[v])
53+
}
54+
})
55+
56+
test('works with empty graph', () => {
57+
const V = 0
58+
const edges = []
59+
const order = kahnTopologicalSort(V, edges)
60+
expect(order).toEqual([])
61+
})
62+
})

0 commit comments

Comments
 (0)