-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0802-find-eventual-safe-states.js
More file actions
40 lines (35 loc) · 1.25 KB
/
0802-find-eventual-safe-states.js
File metadata and controls
40 lines (35 loc) · 1.25 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
/**
* Find Eventual Safe States
* Time Complexity: O(N + E + N log N)
* Space Complexity: O(N + E)
*/
var eventualSafeNodes = function (graph) {
const graphSize = graph.length;
const initialOutDegrees = new Array(graphSize).fill(0);
const reversedAdjacencyList = new Array(graphSize).fill(0).map(() => []);
for (let currentVertex = 0; currentVertex < graphSize; currentVertex++) {
for (let nextVertex of graph[currentVertex]) {
reversedAdjacencyList[nextVertex].push(currentVertex);
initialOutDegrees[currentVertex]++;
}
}
const processingQueue = [];
for (let nodeIdentifier = 0; nodeIdentifier < graphSize; nodeIdentifier++) {
if (initialOutDegrees[nodeIdentifier] === 0) {
processingQueue.push(nodeIdentifier);
}
}
const safeNodesCollection = [];
while (processingQueue.length > 0) {
const processedNode = processingQueue.shift();
safeNodesCollection.push(processedNode);
for (let predecessorNode of reversedAdjacencyList[processedNode]) {
initialOutDegrees[predecessorNode]--;
if (initialOutDegrees[predecessorNode] === 0) {
processingQueue.push(predecessorNode);
}
}
}
safeNodesCollection.sort((valueA, valueB) => valueA - valueB);
return safeNodesCollection;
};