📖 Scenario: Imagine you are building a task manager app. Each task can depend on other tasks to be done first. You want to make sure there are no circular dependencies, which would make it impossible to finish the tasks.
🎯 Goal: You will create a program to detect if there is a cycle in a directed graph representing task dependencies. This will help prevent impossible task orders.
📋 What You'll Learn
Create a directed graph using a dictionary where keys are task names and values are lists of dependent tasks.
Create a helper dictionary to track the visit state of each task.
Implement a function to detect cycles using Depth-First Search (DFS) with recursion.
Print whether a cycle exists or not.
💡 Why This Matters
🌍 Real World
Detecting cycles in task dependencies helps prevent impossible schedules in project management tools.
💼 Career
Cycle detection is important in software engineering for dependency management, build systems, and detecting infinite loops.
Progress0 / 4 steps
1
Create the Directed Graph
Create a dictionary called graph with these exact entries: "A" points to ["B"], "B" points to ["C"], "C" points to ["A"], and "D" points to an empty list [].
DSA C#
Hint
Use a Dictionary<string, List<string>> to represent the graph. Each key is a task, and the value is a list of tasks it points to.
2
Create the Visit State Dictionary
Create a dictionary called visitState with keys "A", "B", "C", and "D", all set to 0. This will track if a task is unvisited (0), visiting (1), or visited (2).
DSA C#
Hint
Use a Dictionary<string, int> to keep track of each task's visit state.
3
Implement Cycle Detection Function
Add a static method called HasCycle that takes string node, Dictionary<string, List<string>> graph, and Dictionary<string, int> visitState. Use DFS to detect cycles: if visitState[node] is 1, return true; if 2, return false; mark 1 before recursion and 2 after. Return true if any neighbor causes a cycle.
DSA C#
Hint
Use recursion and the visitState dictionary to detect cycles. Mark nodes as visiting (1) when you start, and visited (2) when done.
4
Check and Print if Cycle Exists
Use a foreach loop with variable node over graph.Keys. For each node, if visitState[node] is 0 and HasCycle(node, graph, visitState) returns true, print "Cycle detected" and return. If no cycle found, print "No cycle detected".
DSA C#
Hint
Check each node if unvisited. If HasCycle returns true, print "Cycle detected" and stop. Otherwise, print "No cycle detected".
Practice
(1/5)
1. What does cycle detection in a directed graph help us find?
easy
A. Whether there is a path that starts and ends at the same vertex following edge directions
B. The shortest path between two vertices
C. The total number of vertices in the graph
D. The maximum degree of any vertex
Solution
Step 1: Understand cycle in directed graph
A cycle means a path that starts and ends at the same vertex following the direction of edges.
Step 2: Identify what cycle detection finds
Cycle detection checks if such a path exists in the graph.
Final Answer:
Whether there is a path that starts and ends at the same vertex following edge directions -> Option A
Quick Check:
Cycle detection = finding directed cycles [OK]
Hint: Cycle means path loops back following edge directions [OK]
Common Mistakes:
Confusing cycle with shortest path
Ignoring edge directions
Thinking cycle means any repeated vertex
2. Which C# data structure is commonly used to keep track of nodes currently in the recursion stack during DFS for cycle detection?
easy
A. Queue
B. Stack or boolean array to mark recursion stack
C. Dictionary
D. LinkedList
Solution
Step 1: Recall DFS cycle detection method
During DFS, we track nodes in the current recursion path to detect back edges.
Step 2: Identify data structure used
This is done using a stack or a boolean array marking nodes in the recursion stack.
Final Answer:
Stack or boolean array to mark recursion stack -> Option B
A. Missing removing node from visited after recursion
B. Incorrect use of HashSet instead of List
C. Missing adding node to recStack before recursion
D. No bug, code is correct
Solution
Step 1: Check recursion stack usage
Node must be added to recStack before exploring neighbors to detect back edges.
Step 2: Identify missing step
Code adds node to visited but never adds to recStack before recursion, so cycle detection fails.
Final Answer:
Missing adding node to recStack before recursion -> Option C
Quick Check:
recStack update missing = bug [OK]
Hint: Always add node to recursion stack before DFS call [OK]
Common Mistakes:
Forgetting to add node to recursion stack
Removing node from visited incorrectly
Confusing visited and recursion stack roles
5. Given a directed graph represented as adjacency list:
var graph = new Dictionary<int, List<int>> {
{1, new List<int>{2, 3}},
{2, new List<int>{4}},
{3, new List<int>{4}},
{4, new List<int>{5}},
{5, new List<int>{3}}
};
Which nodes form a cycle in this graph?
hard
A. Nodes 3, 4, 5
B. Nodes 1, 2, 4
C. Nodes 2, 3, 5
D. No cycle exists
Solution
Step 1: Trace edges to find cycle
Edges: 3->4, 4->5, 5->3 form a cycle among nodes 3, 4, 5.
Step 2: Confirm cycle presence
Starting at 3, path 3->4->5->3 loops back, confirming cycle.
Final Answer:
Nodes 3, 4, 5 -> Option A
Quick Check:
Cycle nodes = 3,4,5 [OK]
Hint: Follow edges to see if path loops back to start [OK]
Common Mistakes:
Ignoring edge 5->3 that closes cycle
Assuming no cycle because 1 and 2 are acyclic
Confusing cycle nodes with all connected nodes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.