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;