Skip to content

Commit fddebdd

Browse files
authored
feat: kanns Algorithm included
1 parent 9010481 commit fddebdd

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Graphs/KannsAlgorithm.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
/**
3+
* @author {RaviSadam}
4+
* @name kannsAlgorithm
5+
* @description -
6+
* Kann's Algorithm implementation in JavaScript
7+
* @summary
8+
* Kann's Algorithm is used for topological sorting in directed acyclic graphs
9+
*
10+
* @param graph - Graph [[v1,v2],[v3,v4,v5]..]
11+
* @param n - number of vertices
12+
* @returns {Array} - Empty array if cycle is detected or else result array;
13+
*
14+
*/
15+
16+
export function kannsAlgorithm(graph, n) {
17+
if (n === null || n === undefined)
18+
throw Error('Invalid v is given');
19+
const inorder = Array(n).fill(0);
20+
const result = [];
21+
for (let entry of graph) {
22+
for (let edge of entry) {
23+
inorder[edge] += 1;
24+
}
25+
}
26+
const queue = [];
27+
console.log(inorder);
28+
for (let i = 0; i < n; i++) {
29+
if (inorder[i] === 0) {
30+
queue.push(i);
31+
}
32+
}
33+
while (queue.length != 0) {
34+
const node = queue[0];
35+
result.push(node);
36+
queue.splice(0, 1);
37+
for (let nei of graph[node]) {
38+
inorder[nei] -= 1;
39+
if (inorder[nei] == 0) {
40+
queue.push(nei);
41+
}
42+
}
43+
}
44+
if (result.length != n)
45+
return [];
46+
return result;
47+
}

0 commit comments

Comments
 (0)