* Author: Adrito Mukherjee * Kosaraju's Algorithm implementation in Javascript * Kosaraju's Algorithm finds all the connected components in a Directed Acyclic Graph (DAG) * It uses Stack data structure to store the Topological Sorted Order of vertices and also Graph data structure * * Wikipedia
| 9 | */ |
| 10 | |
| 11 | class Kosaraju { |
| 12 | constructor(graph) { |
| 13 | this.connections = {} |
| 14 | this.reverseConnections = {} |
| 15 | this.stronglyConnectedComponents = [] |
| 16 | for (const [i, j] of graph) { |
| 17 | this.addEdge(i, j) |
| 18 | } |
| 19 | this.topoSort() |
| 20 | return this.kosaraju() |
| 21 | } |
| 22 | |
| 23 | addNode(node) { |
| 24 | // Function to add a node to the graph (connection represented by set) |
| 25 | this.connections[node] = new Set() |
| 26 | this.reverseConnections[node] = new Set() |
| 27 | this.topoSorted = [] |
| 28 | } |
| 29 | |
| 30 | addEdge(node1, node2) { |
| 31 | // Function to add an edge (adds the node too if they are not present in the graph) |
| 32 | if (!(node1 in this.connections) || !(node1 in this.reverseConnections)) { |
| 33 | this.addNode(node1) |
| 34 | } |
| 35 | if (!(node2 in this.connections) || !(node2 in this.reverseConnections)) { |
| 36 | this.addNode(node2) |
| 37 | } |
| 38 | this.connections[node1].add(node2) |
| 39 | this.reverseConnections[node2].add(node1) |
| 40 | } |
| 41 | |
| 42 | dfsTopoSort(node, visited) { |
| 43 | visited.add(node) |
| 44 | for (const child of this.connections[node]) { |
| 45 | if (!visited.has(child)) this.dfsTopoSort(child, visited) |
| 46 | } |
| 47 | this.topoSorted.push(node) |
| 48 | } |
| 49 | |
| 50 | topoSort() { |
| 51 | // Function to perform topological sorting |
| 52 | const visited = new Set() |
| 53 | const nodes = Object.keys(this.connections).map((key) => Number(key)) |
| 54 | for (const node of nodes) { |
| 55 | if (!visited.has(node)) this.dfsTopoSort(node, visited) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | dfsKosaraju(node, visited) { |
| 60 | visited.add(node) |
| 61 | this.stronglyConnectedComponents[ |
| 62 | this.stronglyConnectedComponents.length - 1 |
| 63 | ].push(node) |
| 64 | for (const child of this.reverseConnections[node]) { |
| 65 | if (!visited.has(child)) this.dfsKosaraju(child, visited) |
| 66 | } |
| 67 | } |
| 68 |
nothing calls this directly
no outgoing calls
no test coverage detected