|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.1 KB
|
| Line | |
|---|
| 1 | "use strict";
|
|---|
| 2 |
|
|---|
| 3 | module.exports = tarjan;
|
|---|
| 4 |
|
|---|
| 5 | // Adapted from https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#The_algorithm_in_pseudocode
|
|---|
| 6 |
|
|---|
| 7 | function tarjan(graph) {
|
|---|
| 8 | const indices = new Map();
|
|---|
| 9 | const lowlinks = new Map();
|
|---|
| 10 | const onStack = new Set();
|
|---|
| 11 | const stack = [];
|
|---|
| 12 | const scc = [];
|
|---|
| 13 | let idx = 0;
|
|---|
| 14 |
|
|---|
| 15 | function strongConnect(v) {
|
|---|
| 16 | indices.set(v, idx);
|
|---|
| 17 | lowlinks.set(v, idx);
|
|---|
| 18 | idx++;
|
|---|
| 19 | stack.push(v);
|
|---|
| 20 | onStack.add(v);
|
|---|
| 21 |
|
|---|
| 22 | const deps = graph.get(v);
|
|---|
| 23 | for (const dep of deps) {
|
|---|
| 24 | if (!indices.has(dep)) {
|
|---|
| 25 | strongConnect(dep);
|
|---|
| 26 | lowlinks.set(v, Math.min(lowlinks.get(v), lowlinks.get(dep)));
|
|---|
| 27 | } else if (onStack.has(dep)) {
|
|---|
| 28 | lowlinks.set(v, Math.min(lowlinks.get(v), indices.get(dep)));
|
|---|
| 29 | }
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | if (lowlinks.get(v) === indices.get(v)) {
|
|---|
| 33 | const vertices = new Set();
|
|---|
| 34 | let w = null;
|
|---|
| 35 | while (v !== w) {
|
|---|
| 36 | w = stack.pop();
|
|---|
| 37 | onStack.delete(w);
|
|---|
| 38 | vertices.add(w);
|
|---|
| 39 | }
|
|---|
| 40 | scc.push(vertices);
|
|---|
| 41 | }
|
|---|
| 42 | }
|
|---|
| 43 |
|
|---|
| 44 | for (const v of graph.keys()) {
|
|---|
| 45 | if (!indices.has(v)) {
|
|---|
| 46 | strongConnect(v);
|
|---|
| 47 | }
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | return scc;
|
|---|
| 51 | }
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.