-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
root
committed
Jul 8, 2024
1 parent
9010481
commit 74e8ec2
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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([]) | ||
}) |