JavaScript 如何检测含多子节点的层次图中的环路?
多子节点层次图的环路检测实现
核心检测逻辑
当前场景为每个节点关联任意数量子节点的有向层次图,不适用链表场景的快慢指针方案,需基于DFS递归路径状态完成检测,核心判断规则:
- 维护两个独立状态集合:
- 已完成遍历节点集合:该节点的所有关联子节点已全部走完,后续遇到该节点不属于环触发条件
- 当前递归路径栈:记录从遍历起点走到当前节点经过的所有节点,处理子节点时若发现目标子节点已存在于当前路径栈中,即判定形成闭环
可直接运行的检测代码
function detectGraphLoop(graph) { const visited = new Set(); const pathStack = new Set(); let loopPath = null; function dfs(currentNodeKey) { // 命中路径上的重复节点,判定为环 if (pathStack.has(currentNodeKey)) { const pathArr = Array.from(pathStack); const startIdx = pathArr.indexOf(currentNodeKey); loopPath = [...pathArr.slice(startIdx), currentNodeKey]; return true; } // 已完成全量遍历的节点无需重复处理 if (visited.has(currentNodeKey)) return false; pathStack.add(currentNodeKey); // 遍历当前节点所有关联子节点 const children = graph[currentNodeKey]?.children || []; for (const childKey of children) { if (dfs(childKey)) return true; } // 当前节点分支走完,移出路径栈、加入已完成集合 pathStack.delete(currentNodeKey); visited.add(currentNodeKey); return false; } // 遍历所有顶层节点,避免多连通图漏检 for (const nodeKey of Object.keys(graph)) { if (dfs(nodeKey)) { return { hasLoop: true, loopPath }; } } return { hasLoop: false, loopPath: null }; }
示例验证结果
补全示例中省略的节点定义后,检测逻辑可精准命中a -> b -> c -> a的环路:
const graph = { a: {value: 'Va', children: ['b', 'd']}, b: {value: 'Vb', children: ['c']}, c: {value: 'Vc', children: ['a', 'd', 'e']}, d: {value: 'Vd', children: []}, e: {value: 'Ve', children: []} } // 调用detectGraphLoop(graph)的输出 // { hasLoop: true, loopPath: ['a', 'b', 'c', 'a'] }
方案特性
- 检测过程不修改原图的节点结构,所有状态通过外部集合维护,不会污染原业务数据
- 兼容存在多个独立连通分支的图结构,不会因提前返回检测结果漏检其他分支的环路
- 时间复杂度与图的节点数、边数线性相关,对大规模层次图的检测效率可控
内容的提问来源于stack exchange,提问作者1man
相关产品推荐
相关产品推荐

