Skip to content

Commit 9f3aa64

Browse files
author
root
committed
Updated kahn's algorithm
1 parent 74e8ec2 commit 9f3aa64

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Graphs/KahnsAlgorithm.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import Queue from '../Data-Structures/Queue/Queue'
2+
3+
/**
4+
* @author {RaviSadam}
5+
* @name KahnsAlgorithm
6+
* @description -
7+
* Kahn's Algorithm implementation in JavaScript
8+
* @summary
9+
* Kahn's Algorithm is used for finding the topological sorting order of directed acyclic graph
10+
*
11+
* @param graph - Graph (adjacency list)
12+
* @param n - Size of graph
13+
* @returns {Array} - null if cycle is detected or else result array
14+
*
15+
*/
16+
17+
export function KahnsAlgorithm(graph, n) {
18+
if (n === null || n === undefined) throw Error('Invalid n was given')
19+
const inDegree = Array(n).fill(0)
20+
const result = []
21+
for (const neigbhours of graph) {
22+
for (const neigbhour of neigbhours) {
23+
inDegree[neigbhour] += 1
24+
}
25+
}
26+
const queue = new Queue()
27+
28+
for (let i = 0; i < n; i++) {
29+
if (inDegree[i] === 0) {
30+
queue.enqueue(i)
31+
}
32+
}
33+
while (queue.length !== 0) {
34+
const node = queue.dequeue()
35+
result.push(node)
36+
for (const neigbhour of graph[node]) {
37+
inDegree[neigbhour] -= 1
38+
if (inDegree[neigbhour] == 0) {
39+
queue.enqueue(neigbhour)
40+
}
41+
}
42+
}
43+
if (result.length !== n) return null
44+
return result
45+
}

Graphs/test/KahnsAlgorithm.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { KahnsAlgorithm } from '../KahnsAlgorithm'
2+
3+
test('Graph without cycle', () => {
4+
const graph = [[], [], [3], [1], [0, 1], [0, 2]]
5+
6+
expect(KahnsAlgorithm(graph, 6)).toEqual([4, 5, 0, 2, 3, 1])
7+
})
8+
9+
test('Graph with cycle', () => {
10+
const graph = [[2], [], [3, 5], [0, 1], [0, 2]]
11+
12+
expect(KahnsAlgorithm(graph, 6)).toBe(null)
13+
})

0 commit comments

Comments
 (0)