Skip to content
Advertisement

JavaScript: Detect a Loop in a Hierarchical Graph

Note that I’ve already gone through How to detect a loop in a hierarchy of javascript elements In our case, we’re not dealing with a linked-list, but a hierarchical graph where each node may have multiple children linked to it. For example,

JavaScript

In this graph, we should detect the loop a -> b -> c -> a.

Advertisement

Answer

If you only need to determine whether a graph has a cycle, and don’t need to report what the cycle is, you can do this for a particular node of the graph with a simple recursion and wrap that in a call that tests all nodes.

Here’s one implementation:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement