fix: self-loop / root node cycle detection in undirected graph

This commit is contained in:
chenluli 2020-08-08 12:18:05 +08:00 committed by Moyee
parent a8971903ca
commit 3e1f1156d4

View File

@ -108,19 +108,20 @@ export const detectAllUndirectedCycle = (graph: IGraph, nodeIds?: string[], incl
for (let i = 0; i < neighbors.length; i += 1) {
const neighbor = neighbors[i]
const neighborId = neighbor.get('id')
if (!(neighborId in used)) { // visit a new node
if (neighborId === curNodeId) { // 自环
allCycles.push({ [neighbor.getID()]: curNode })
} else if (!(neighborId in used)) {// visit a new node
parent[neighborId] = curNode
stack.push(neighbor)
used[neighborId] = new Set([curNode])
} else if (neighborId === curNodeId) {// 自环
allCycles.push({ [neighbor.getID()]: curNode })
} else if (!used[curNodeId].has(neighbor)) { // a cycle found
let cycleValid = true
const cyclePath = [neighbor, curNode]
let p = parent[curNodeId]
while (used[neighborId].size && !used[neighborId].has(p)) {
cyclePath.push(p)
p = parent[p.getID()]
if (p === parent[p.getID()]) break
else p = parent[p.getID()]
}
cyclePath.push(p)