|
|
|
@ -1,4 +1,4 @@
|
|
|
|
|
export default function checkGraphForCycles(edges: Array<[any, any]>): any[] {
|
|
|
|
|
export default function check_graph_for_cycles(edges: Array<[any, any]>): any[] {
|
|
|
|
|
const graph: Map<any, any[]> = edges.reduce((g, edge) => {
|
|
|
|
|
const [u, v] = edge;
|
|
|
|
|
if (!g.has(u)) g.set(u, []);
|
|
|
|
@ -8,22 +8,22 @@ export default function checkGraphForCycles(edges: Array<[any, any]>): any[] {
|
|
|
|
|
}, new Map());
|
|
|
|
|
|
|
|
|
|
const visited = new Set();
|
|
|
|
|
const onStack = new Set();
|
|
|
|
|
const on_stack = new Set();
|
|
|
|
|
const cycles = [];
|
|
|
|
|
|
|
|
|
|
function visit (v) {
|
|
|
|
|
visited.add(v);
|
|
|
|
|
onStack.add(v);
|
|
|
|
|
on_stack.add(v);
|
|
|
|
|
|
|
|
|
|
graph.get(v).forEach(w => {
|
|
|
|
|
if (!visited.has(w)) {
|
|
|
|
|
visit(w);
|
|
|
|
|
} else if (onStack.has(w)) {
|
|
|
|
|
cycles.push([...onStack, w]);
|
|
|
|
|
} else if (on_stack.has(w)) {
|
|
|
|
|
cycles.push([...on_stack, w]);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
onStack.delete(v);
|
|
|
|
|
on_stack.delete(v);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
graph.forEach((_, v) => {
|