-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathKahnsAlgorithm.test.js
More file actions
62 lines (52 loc) · 1.35 KB
/
KahnsAlgorithm.test.js
File metadata and controls
62 lines (52 loc) · 1.35 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { kahnTopologicalSort } from '../KahnsAlgorithm.js'
describe("Kahn's Algorithm - Topological Sort", () => {
test('returns a valid topological order for a DAG', () => {
const V = 6
const edges = [
[5, 2],
[5, 0],
[4, 0],
[4, 1],
[2, 3],
[3, 1]
]
const order = kahnTopologicalSort(V, edges)
expect(order.length).toBe(V)
// verify topological property
const pos = new Array(V)
for (let i = 0; i < order.length; i++) pos[order[i]] = i
for (const [u, v] of edges) {
expect(pos[u]).toBeLessThan(pos[v])
}
})
test('returns empty array when graph contains a cycle', () => {
const V = 3
const edges = [
[0, 1],
[1, 2],
[2, 0] // cycle
]
const order = kahnTopologicalSort(V, edges)
expect(order).toEqual([])
})
test('includes isolated nodes', () => {
const V = 4
const edges = [
[0, 1],
[2, 3]
]
const order = kahnTopologicalSort(V, edges)
expect(order.length).toBe(V)
const pos = new Array(V)
for (let i = 0; i < order.length; i++) pos[order[i]] = i
for (const [u, v] of edges) {
expect(pos[u]).toBeLessThan(pos[v])
}
})
test('works with empty graph', () => {
const V = 0
const edges = []
const order = kahnTopologicalSort(V, edges)
expect(order).toEqual([])
})
})