Skip to content

Commit

Permalink
feat:added kanns algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Jul 8, 2024
1 parent 9010481 commit 74e8ec2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
44 changes: 44 additions & 0 deletions Graphs/KannsAlgorithm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* @author {RaviSadam}
* @name kannsAlgorithm
* @description -
* Kann's Algorithm implementation in JavaScript
* @summary
* Kann's Algorithm is used for topological sorting in directed acyclic graphs
*
* @param graph - Graph [[v1,v2],[v3,v4,v5]..]
* @param n - number of vertices
* @returns {Array} - Empty array if cycle is detected or else result array;
*
*/

export function kannsAlgorithm(graph, n) {
if (n === null || n === undefined) throw Error('Invalid n was given')
const inorder = Array(n).fill(0)
const result = []
for (let entry of graph) {
for (let edge of entry) {
inorder[edge] += 1
}
}
const queue = []
console.log(inorder)
for (let i = 0; i < n; i++) {
if (inorder[i] === 0) {
queue.push(i)
}
}
while (queue.length != 0) {
const node = queue[0]
result.push(node)
queue.splice(0, 1)
for (let nei of graph[node]) {
inorder[nei] -= 1
if (inorder[nei] == 0) {
queue.push(nei)
}
}
}
if (result.length != n) return []
return result
}
13 changes: 13 additions & 0 deletions Graphs/test/KannsAlgorithm.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { kannsAlgorithm } from '../KannsAlgorithm'

test('Test Case 1: Graph without cycle', () => {
const graph = [[], [], [3], [1], [0, 1], [0, 2]]

expect(kannsAlgorithm(graph, 6)).toEqual([4, 5, 0, 2, 3, 1])
})

test('Test Case 2: Graph with cycle', () => {
const graph = [[2], [], [3, 5], [0, 1], [0, 2]]

expect(kannsAlgorithm(graph, 6)).toEqual([])
})

0 comments on commit 74e8ec2

Please sign in to comment.