From 0b34d7d963f67699d34ed9df714fbabb4e986400 Mon Sep 17 00:00:00 2001 From: Gonzalo Blasco Date: Wed, 5 Aug 2026 05:37:48 -0300 Subject: [PATCH] fix(#2057): return ordered cycle path array instead of parent mapping in detectUndirectedCycle The function was returning an object mapping vertex keys to their parent vertices, which is not a standard cycle representation. Changed to return an ordered array of vertices forming the cycle, starting and ending at the same vertex. Fixes #2057 --- .../__test__/detectUndirectedCycle.test.js | 13 +++++++------ .../graph/detect-cycle/detectUndirectedCycle.js | 12 ++++++------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js b/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js index c3f9903102..76c0778c14 100644 --- a/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js +++ b/src/algorithms/graph/detect-cycle/__test__/detectUndirectedCycle.test.js @@ -31,11 +31,12 @@ describe('detectUndirectedCycle', () => { graph.addEdge(edgeDE); - expect(detectUndirectedCycle(graph)).toEqual({ - B: vertexC, - C: vertexD, - D: vertexE, - E: vertexB, - }); + expect(detectUndirectedCycle(graph)).toEqual([ + vertexB, + vertexC, + vertexD, + vertexE, + vertexB, + ]); }); }); diff --git a/src/algorithms/graph/detect-cycle/detectUndirectedCycle.js b/src/algorithms/graph/detect-cycle/detectUndirectedCycle.js index 5bcc9bb699..bfac742a1c 100644 --- a/src/algorithms/graph/detect-cycle/detectUndirectedCycle.js +++ b/src/algorithms/graph/detect-cycle/detectUndirectedCycle.js @@ -30,19 +30,19 @@ export default function detectUndirectedCycle(graph) { }, enterVertex: ({ currentVertex, previousVertex }) => { if (visitedVertices[currentVertex.getKey()]) { - // Compile cycle path based on parents of previous vertices. - cycle = {}; + // Build an ordered cycle path array starting and ending at the repeated vertex. + const cyclePath = [currentVertex]; - let currentCycleVertex = currentVertex; let previousCycleVertex = previousVertex; while (previousCycleVertex.getKey() !== currentVertex.getKey()) { - cycle[currentCycleVertex.getKey()] = previousCycleVertex; - currentCycleVertex = previousCycleVertex; + cyclePath.push(previousCycleVertex); previousCycleVertex = parents[previousCycleVertex.getKey()]; } - cycle[currentCycleVertex.getKey()] = previousCycleVertex; + cyclePath.push(previousCycleVertex); + + cycle = cyclePath; } else { // Add next vertex to visited set. visitedVertices[currentVertex.getKey()] = currentVertex;