Skip to content

Commit 2969d70

Browse files
committed
[FEATURE]: Add Kahn's Algorithm in Graphs #1795
1 parent e123b19 commit 2969d70

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const { kahnTopologicalSort } = require('../KahnsAlgorithm');
2+
3+
describe("Kahn's Algorithm", () => {
4+
test('DAG returns valid topological order', () => {
5+
const V = 6;
6+
const edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]];
7+
const order = kahnTopologicalSort(V, edges);
8+
expect(order.length).toBe(V);
9+
const pos = Array(V);
10+
for (let i = 0; i < order.length; i++) pos[order[i]] = i;
11+
for (const [u,v] of edges) expect(pos[u]).toBeLessThan(pos[v]);
12+
});
13+
14+
test('Cycle returns empty array', () => {
15+
const V = 3;
16+
const edges = [[0,1],[1,2],[2,0]];
17+
expect(kahnTopologicalSort(V, edges)).toEqual([]);
18+
});
19+
20+
test('Includes isolated nodes', () => {
21+
const V = 4;
22+
const edges = [[0,1],[2,3]];
23+
const order = kahnTopologicalSort(V, edges);
24+
expect(order.length).toBe(V);
25+
const pos = Array(V);
26+
for (let i = 0; i < order.length; i++) pos[order[i]] = i;
27+
for (const [u,v] of edges) expect(pos[u]).toBeLessThan(pos[v]);
28+
});
29+
});

0 commit comments

Comments
 (0)