From the course: Data Structures in JavaScript: Trees and Graphs

Cycle-detection concept

- [Instructor] Now that you've got a solid understanding of the concepts and practical applications, like representing tasks with dependencies in a DAG and efficiently soaring them using recursion, it's time to introduce a wrench, cycle detection during topological sort. This will build on what you've already learned while adding a layer of complexity. Specific properties and assumptions break down if a cycle exists, so handling the scenario is essential. For example, if you're scheduling tasks with dependencies, a cycle would mean some tasks can't be completed due to circular prerequisites. Modifying our graph example from the previous lesson, a directed edge from K to D will break the properties of a DAG, and our algorithm has to handle this corner case. Let's walk through what happens using our original topological sort algorithm. Notice that visiting J for the second time, it should throw an error and end the algorithm because the graph is verified not to be a DAG. Let's walk through how to catch this error. We would need another set similar to the visited set to throw an error properly. The difference between the visited set and this new set we will call ancestor will be that the ancestor set will track nodes into current DFS path, whereas the visited set tracks all nodes visited through the entire algorithm. We start by picking a random node. For the sake of the example, suppose we begin DFS from A first. B visit A and add it to our visited and ancestor sets. Then suppose we start the DFS path through C. We add C to both our sets. On the backtrack, we add C to our ordering and remove C from the ancestor set. From A, we then DFS through D. In topological sorting with cycle detection, it's crucial to distinguish between the visited set and ancestor set. The visited set records all nodes explored to prevent redundant processing. While the ancestor set tracks the current DFS path containing only direct ancestors of the visited node. Think of the visited set as a record of all places you've been, and the ancestor set as a specific trail leading to your current location. A cycle is detected if a node reappears in the ancestor set indicating a loop in the graph. This dual tracking ensures efficient cycle detection and correct topological ordering.

Contents