Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/alg/find-cycles.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {Graph} from '../graph';
import type {Edge} from '../types';
import {tarjan} from './tarjan';

/**
Expand All @@ -14,6 +15,10 @@ import {tarjan} from './tarjan';
*/
export function findCycles(graph: Graph): string[][] {
return tarjan(graph).filter(function (cmpt) {
return cmpt.length > 1 || (cmpt.length === 1 && graph.hasEdge(cmpt[0]!, cmpt[0]!));
// A single-node component is a cycle iff the node has a self-loop. We check via outEdges
// rather than hasEdge(v, v) because the latter only matches the default (unnamed) edge and
// would miss a named self-loop edge in a multigraph.
return cmpt.length > 1
|| (cmpt.length === 1 && (graph.outEdges(cmpt[0]!, cmpt[0]!) as Edge[]).length > 0);
});
}
7 changes: 7 additions & 0 deletions test/alg/find-cycles-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ describe("alg.findCycles", () => {
expect(sort(findCycles(g))).toEqual([["a", "b", "c"]]);
});

it("detects a self-loop created with a named edge in a multigraph", () => {
const g = new Graph({multigraph: true});
g.setNode("a");
g.setEdge("a", "a", "label", "name");
expect(sort(findCycles(g))).toEqual([["a"]]);
});

it("returns multiple entries for multiple cycles", () => {
const g = new Graph();
g.setPath(["a", "b", "a"]);
Expand Down