📖 Scenario: Imagine you are building a task manager app. Each task can depend on other tasks to be completed first. This creates a directed graph where tasks point to their dependencies. You want to check if there is a cycle in these dependencies, which would make it impossible to complete all tasks.
🎯 Goal: Build a program to detect if a directed graph of tasks has a cycle. You will represent the graph as an adjacency list, then write code to detect cycles using depth-first search.
📋 What You'll Learn
Create a directed graph as an adjacency list using a JavaScript object
Add a helper variable to track visited nodes
Implement a depth-first search function to detect cycles
Print whether the graph contains a cycle or not
💡 Why This Matters
🌍 Real World
Cycle detection is important in task scheduling, dependency resolution, and deadlock detection in operating systems.
💼 Career
Understanding cycle detection helps in software development roles involving graph algorithms, backend systems, and project management tools.
Progress0 / 4 steps
1
Create the directed graph as an adjacency list
Create a JavaScript object called graph representing a directed graph with these edges: 1 -> 2, 2 -> 3, 3 -> 4, 4 -> 2, and 4 -> 5. Use numbers as keys and arrays of numbers as values.
DSA Javascript
Hint
Use an object where each key is a node number and the value is an array of nodes it points to.
2
Add helper variables to track visited nodes
Add two JavaScript objects called visited and recStack to track visited nodes and nodes in the current recursion stack. Initialize both as empty objects.
DSA Javascript
Hint
Use empty objects to mark nodes as visited or currently in the recursion stack.
3
Implement the depth-first search function to detect cycles
Write a function called isCyclicUtil that takes a node v and returns true if a cycle is detected starting from v. Use visited and recStack to track nodes. Mark v as visited and add it to recStack. For each neighbor of v in graph[v], if it is not visited, recursively call isCyclicUtil. If a neighbor is in recStack, return true. Remove v from recStack before returning false. Then write a function called isCyclic that checks all nodes in graph by calling isCyclicUtil and returns true if any call returns true.
DSA Javascript
Hint
Use recursion to explore neighbors. Track nodes in the current path with recStack to detect cycles.
4
Print whether the graph contains a cycle
Write a console.log statement to print "Graph contains cycle" if isCyclic() returns true, otherwise print "Graph does not contain cycle".
DSA Javascript
Hint
Call isCyclic() and print the result with console.log.
Practice
(1/5)
1. What is the main purpose of cycle detection in a directed graph?
easy
A. To find if there is a path that starts and ends at the same node following the direction of edges
B. To count the total number of edges in the graph
C. To find the shortest path between two nodes
D. To check if the graph is connected
Solution
Step 1: Understand cycle in directed graph
A cycle means a path that starts and ends at the same node following edge directions.
Step 2: Purpose of cycle detection
Cycle detection checks if such a path exists in the graph.
Final Answer:
To find if there is a path that starts and ends at the same node following the direction of edges -> Option A
Quick Check:
Cycle detection = find directed loops [OK]
Hint: Cycle means a directed loop returning to start [OK]
Common Mistakes:
Confusing cycle detection with counting edges
Thinking cycle detection finds shortest paths
Assuming cycle detection checks connectivity
2. Which of the following JavaScript code snippets correctly initializes a graph as an adjacency list for cycle detection?
easy
A. const graph = {0: [1, 2], 1: [2], 2: [0]};
B. const graph = [[0,1], [1,2], [2,0]];
C. const graph = new Map([0, [1, 2], 1, [2], 2, [0]]);
Which of the following modifications will break the cycle detection algorithm that uses DFS with a recursion stack?
hard
A. Starting DFS from node 0 instead of node 4
B. Adding a visited set to track visited nodes
C. Removing the recursion stack and using only a visited set
D. Using an iterative BFS instead of DFS
Solution
Step 1: Understand the role of recursion stack in cycle detection
The recursion stack tracks nodes in the current path to detect cycles (back edges).
Step 2: Effect of removing recursion stack
Without recursion stack, the algorithm cannot detect cycles correctly, even if visited set is used.
Step 3: Other options explained
Adding visited set helps. Starting DFS from different nodes does not break detection if all nodes are visited. Using BFS does not detect cycles in directed graphs reliably.
Final Answer:
Removing the recursion stack and using only a visited set -> Option C
Quick Check:
Recursion stack needed for cycle detection [OK]
Hint: Recursion stack is essential for detecting cycles in DFS [OK]