Skip to content

Commit

Permalink
Add Tarjan SCC algorithm implementation
Browse files Browse the repository at this point in the history
Adds an implementation of Tarjan's algorithm to find strongly connected
components.

This will be used on the experimental bundler to simplify cycle handling and
can be used on other parts of the codebase to simplify the symbol propagation
implementation.

On the bundler, we will use this to convert the graph to an acyclic graph
(replace the strongly connected components with a single 'group' node) before
doing other work.

Test Plan: yarn test

Reviewers: JakeLane

Reviewed By: JakeLane

Pull Request: #332
  • Loading branch information
yamadapc authored Feb 7, 2025
1 parent 2d2c23f commit 719a782
Show file tree
Hide file tree
Showing 2 changed files with 160 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// @flow strict-local

import type {Graph, NodeId} from '@atlaspack/graph';

export type StronglyConnectedComponent = NodeId[];

/**
* Robert Tarjan's algorithm to find strongly connected components in a graph.
*
* Time complexity: O(V + E)
* Space complexity (worst case): O(V)
*
* * https://web.archive.org/web/20170829214726id_/http://www.cs.ucsb.edu/~gilbert/cs240a/old/cs240aSpr2011/slides/TarjanDFS.pdf
* * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*/
export function findStronglyConnectedComponents<T, E: number>(
graph: Graph<T, E>,
): StronglyConnectedComponent[] {
type State = {|
index: null | NodeId,
lowlink: null | NodeId,
onStack: boolean,
|};
const result = [];
let index = 0;
const stack = [];
const state: State[] = new Array(graph.nodes.length).fill(null).map(() => ({
index: null,
lowlink: null,
onStack: false,
}));
graph.nodes.forEach((node, nodeId) => {
if (node != null && state[nodeId].index == null) {
strongConnect(nodeId);
}
});
function strongConnect(nodeId) {
const nodeState = state[nodeId];
nodeState.index = index;
nodeState.lowlink = index;

index += 1;

stack.push(nodeId);
nodeState.onStack = true;

for (let neighborId of graph.getNodeIdsConnectedFrom(nodeId)) {
const neighborState = state[neighborId];
if (neighborState.index == null) {
strongConnect(neighborId);

nodeState.lowlink = Math.min(
Number(nodeState.lowlink),
Number(neighborState.lowlink),
);
} else if (neighborState.onStack) {
nodeState.lowlink = Math.min(
Number(nodeState.lowlink),
Number(neighborState.index),
);
}
}

if (nodeState.lowlink === nodeState.index) {
const component = [];
let member;

do {
member = stack.pop();
state[member].onStack = false;
component.push(member);
} while (member !== nodeId);

result.push(component);
}
}

return result;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// @flow strict-local

import {Graph} from '@atlaspack/graph';
import assert from 'assert';
import {findStronglyConnectedComponents} from '../../../src/DominatorBundler/cycleBreaker/findStronglyConnectedComponents';

describe('findStronglyConnectedComponents', () => {
it('should find strongly connected components', () => {
/*
digraph graph {
root -> a;
a -> b;
b -> a;
c;
}
*/
const graph = new Graph();
const root = graph.addNode('root');
graph.setRootNodeId(root);
const a = graph.addNode('a');
const b = graph.addNode('b');
const c = graph.addNode('c');

graph.addEdge(root, a);
graph.addEdge(a, b);
graph.addEdge(b, a);

const result = findStronglyConnectedComponents(graph);

assert.deepStrictEqual(result, [[b, a], [root], [c]]);
});

it('works over an empty graph with a root', () => {
/*
digraph graph {
root;
}
*/
const graph = new Graph();
const root = graph.addNode('root');
graph.setRootNodeId(root);

const result = findStronglyConnectedComponents(graph);
assert.deepStrictEqual(result, [[root]]);
});

it('works over an empty graph', () => {
/*
digraph graph {
}
*/
const graph = new Graph();

const result = findStronglyConnectedComponents(graph);
assert.deepStrictEqual(result, []);
});

it('returns all nodes if there are no cycles', () => {
/*
digraph graph {
root -> a;
a -> b;
b -> c;
}
*/
const graph = new Graph();
const root = graph.addNode('root');
graph.setRootNodeId(root);
const a = graph.addNode('a');
const b = graph.addNode('b');
const c = graph.addNode('c');

graph.addEdge(root, a);
graph.addEdge(a, b);
graph.addEdge(b, c);

const result = findStronglyConnectedComponents(graph);

assert.deepStrictEqual(result, [[c], [b], [a], [root]]);
});
});

0 comments on commit 719a782

Please sign in to comment.