diff --git a/Graphs/KannsAlgorithm.js b/Graphs/KannsAlgorithm.js new file mode 100644 index 0000000000..1b9cb43540 --- /dev/null +++ b/Graphs/KannsAlgorithm.js @@ -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 +} diff --git a/Graphs/test/KannsAlgorithm.test.js b/Graphs/test/KannsAlgorithm.test.js new file mode 100644 index 0000000000..3c00495b78 --- /dev/null +++ b/Graphs/test/KannsAlgorithm.test.js @@ -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([]) +})