forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKosaraju.js
More file actions
Latest commit
100 lines (89 loc) · 2.62 KB
/
Copy pathKosaraju.js
File metadata and controls
100 lines (89 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* 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: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm
*
*/
classKosaraju{
constructor(graph){
this.connections={}
this.reverseConnections={}
this.stronglyConnectedComponents=[]
for(const[i,j]ofgraph){
this.addEdge(i,j)
}
this.topoSort()
returnthis.kosaraju()
}
addNode(node){
// Function to add a node to the graph (connection represented by set)
this.connections[node]=newSet()
this.reverseConnections[node]=newSet()
this.topoSorted=[]
}
addEdge(node1,node2){
// Function to add an edge (adds the node too if they are not present in the graph)
if(!(node1inthis.connections)||!(node1inthis.reverseConnections)){
this.addNode(node1)
}
if(!(node2inthis.connections)||!(node2inthis.reverseConnections)){
this.addNode(node2)
}
this.connections[node1].add(node2)
this.reverseConnections[node2].add(node1)
}
dfsTopoSort(node,visited){
visited.add(node)
for(constchildofthis.connections[node]){
if(!visited.has(child))this.dfsTopoSort(child,visited)
}
this.topoSorted.push(node)
}
topoSort(){
// Function to perform topological sorting
constvisited=newSet()
constnodes=Object.keys(this.connections).map((key)=>Number(key))
for(constnodeofnodes){
if(!visited.has(node))this.dfsTopoSort(node,visited)
}
}
dfsKosaraju(node,visited){
visited.add(node)
this.stronglyConnectedComponents[
this.stronglyConnectedComponents.length-1
].push(node)
for(constchildofthis.reverseConnections[node]){
if(!visited.has(child))this.dfsKosaraju(child,visited)
}
}
kosaraju(){
// Function to perform Kosaraju Algorithm
constvisited=newSet()
while(this.topoSorted.length>0){
constnode=this.topoSorted.pop()
if(!visited.has(node)){
this.stronglyConnectedComponents.push([])
this.dfsKosaraju(node,visited)
}
}
returnthis.stronglyConnectedComponents
}
}
functionkosaraju(graph){
conststronglyConnectedComponents=newKosaraju(graph)
returnstronglyConnectedComponents
}
export{kosaraju}
// kosaraju([
// [1, 2],
// [2, 3],
// [3, 1],
// [2, 4],
// [4, 5],
// [5, 6],
// [6, 4],
// ])
// [ [ 1, 3, 2 ], [ 4, 6, 5 ] ]