Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix(graph): return ordered cycle path and add early exit in detectUndirectedCycle #2080

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
punit1009 wants to merge 5 commits into trekhleb:master
base: master
Choose a base branch
Loading
from punit1009:fix/detect-undirected-cycle-#2057
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
Binary file added .gitattributes
View file Open in desktop
Binary file not shown.
8 changes: 7 additions & 1 deletion .husky/.gitignore
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
_
# Enforce LF for all text files
* text=auto eol=lf

# Ignore all files in .husky except .sh scripts
*
!.gitignore
!*.sh
5 changes: 0 additions & 5 deletions .husky/pre-commit
View file Open in desktop

This file was deleted.

View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,40 @@ describe('detectUndirectedCycle', () => {
.addEdge(edgeBC)
.addEdge(edgeCD);

// no cycle yet
expect(detectUndirectedCycle(graph)).toBeNull();

// add the final edge that closes cycle B-C-D-E-B
graph.addEdge(edgeDE);

expect(detectUndirectedCycle(graph)).toEqual({
B: vertexC,
C: vertexD,
D: vertexE,
E: vertexB,
const cycle = detectUndirectedCycle(graph);

// should return ordered array of vertices representing cycle (first === last)
expect(Array.isArray(cycle)).toBe(true);
expect(cycle.length).toBeGreaterThanOrEqual(3);
expect(cycle[0].getKey()).toBe(cycle[cycle.length - 1].getKey());

// Extract keys for easier assertions
const keys = cycle.map((v) => v.getKey());

// The expected cycle is B -> C -> D -> E -> B (but the returned cycle may be a rotation),
// so accept any rotation of that sequence.
const allowedRotations = [
['B', 'C', 'D', 'E', 'B'],
['C', 'D', 'E', 'B', 'C'],
['D', 'E', 'B', 'C', 'D'],
['E', 'B', 'C', 'D', 'E'],
];

// Check that keys match one of the allowed rotations
const matchesRotation = allowedRotations.some((rot) => {
if (rot.length !== keys.length) return false;
for (let i = 0; i < rot.length; i += 1) {
if (rot[i] !== keys[i]) return false;
}
return true;
});

expect(matchesRotation).toBe(true);
});
});
57 changes: 29 additions & 28 deletions src/algorithms/graph/detect-cycle/detectUndirectedCycle.js
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,57 @@ import depthFirstSearch from '../depth-first-search/depthFirstSearch';
* Detect cycle in undirected graph using Depth First Search.
*
* @param {Graph} graph
* @returns {Vertex[] | null} ordered array of vertices forming the cycle (first === last), or null
*/
export default function detectUndirectedCycle(graph) {
let cycle = null;
let cycle = null; // will hold ordered array once found

// List of vertices that we have visited.
const visitedVertices = {};
const visitedVertices = {}; // visited vertices
const parents = {}; // parent for every visited vertex

// List of parents vertices for every visited vertex.
const parents = {};

// Callbacks for DFS traversing.
const callbacks = {
allowTraversal: ({ currentVertex, nextVertex }) => {
// Don't allow further traversal in case if cycle has been detected.
if (cycle) {
return false;
}
if (cycle) return false; // stop traversal once cycle is found

// Don't allow traversal from child back to its parent.
const currentVertexParent = parents[currentVertex.getKey()];
const currentVertexParentKey = currentVertexParent ? currentVertexParent.getKey() : null;
const currentVertexParentKey = currentVertexParent
? currentVertexParent.getKey()
: null;

return currentVertexParentKey !== nextVertex.getKey();
},

enterVertex: ({ currentVertex, previousVertex }) => {
if (visitedVertices[currentVertex.getKey()]) {
// Compile cycle path based on parents of previous vertices.
cycle = {};

let currentCycleVertex = currentVertex;
let previousCycleVertex = previousVertex;

while (previousCycleVertex.getKey() !== currentVertex.getKey()) {
cycle[currentCycleVertex.getKey()] = previousCycleVertex;
currentCycleVertex = previousCycleVertex;
previousCycleVertex = parents[previousCycleVertex.getKey()];
// Build ordered cycle array
const startKey = currentVertex.getKey();
const cycleArr = [currentVertex];

let walker = previousVertex;
while (walker && walker.getKey() !== startKey) {
cycleArr.push(walker);
walker = parents[walker.getKey()];
}

cycle[currentCycleVertex.getKey()] = previousCycleVertex;
cycleArr.push(currentVertex); // close the cycle
cycle = cycleArr;
} else {
// Add next vertex to visited set.
visitedVertices[currentVertex.getKey()] = currentVertex;
parents[currentVertex.getKey()] = previousVertex;
}
},
};

// Start DFS traversing.
const startVertex = graph.getAllVertices()[0];
depthFirstSearch(graph, startVertex, callbacks);
const allVertices = graph.getAllVertices();
for (let i = 0; i < allVertices.length; i += 1) {
const startVertex = allVertices[i];

if (!visitedVertices[startVertex.getKey()]) {
depthFirstSearch(graph, startVertex, callbacks);

if (cycle) break; // early exit once cycle is found
}
}

return cycle;
}

AltStyle によって変換されたページ (->オリジナル) /