📖 Scenario: Imagine you are building a task scheduler that runs tasks in order. Some tasks depend on others. If there is a loop in dependencies, the scheduler cannot run tasks properly.We will detect if there is a cycle in the task dependency graph.
🎯 Goal: Create a program to detect if a directed graph has a cycle using depth-first search.
📋 What You'll Learn
Create a directed graph using adjacency list representation
Use arrays to track visited nodes and recursion stack
Implement a recursive 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, deadlock detection, and dependency resolution in software projects.
💼 Career
Understanding cycle detection helps in roles like software developer, system engineer, and data engineer where graph algorithms are used.
Progress0 / 4 steps
1
Create the Directed Graph
Create an integer variable V and set it to 4. Create an adjacency list called graph as an array of ArrayList<Integer> with size V. Initialize each element of graph with a new ArrayList<>. Add edges to graph as follows: from 0 to 1, from 1 to 2, from 2 to 3, and from 3 to 1.
DSA Java
Hint
Use an array of ArrayLists to represent the graph. Initialize each list before adding edges.
2
Add Visited and Recursion Stack Arrays
Create two boolean arrays called visited and recStack of size V. Initialize both arrays with false values.
DSA Java
Hint
Use new boolean[V] to create arrays initialized with false.
3
Implement Recursive Cycle Detection Function
Create a static method boolean isCyclicUtil(int v) that returns true if a cycle is found starting from vertex v. Inside it, mark visited[v] and recStack[v] as true. For each neighbor n in graph[v], if visited[n] is false, recursively call isCyclicUtil(n) and return true if it returns true. If recStack[n] is true, return true. After visiting neighbors, set recStack[v] to false and return false.
DSA Java
Hint
Use recursion to visit neighbors. Track nodes in the recursion stack to detect cycles.
4
Detect Cycle and Print Result
In the main method, create a boolean variable hasCycle and set it to false. Use a for loop from 0 to V - 1. For each vertex i, if visited[i] is false, call isCyclicUtil(i). If it returns true, set hasCycle to true and break the loop. Finally, print "Graph contains cycle" if hasCycle is true, else print "Graph does not contain cycle".
DSA Java
Hint
Loop through all vertices and use the recursive function to detect cycles. Print the result accordingly.
Practice
(1/5)
1. What does cycle detection in a directed graph help us find?
easy
A. The maximum degree of any node
B. The shortest path between two nodes
C. The total number of nodes in the graph
D. Whether there is a path that starts and ends at the same node following the direction of edges
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: 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 node following the direction of edges -> Option D
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 node without direction
2. Which Java data structure is commonly used to keep track of nodes currently in the recursion stack during DFS for cycle detection?
easy
A. Stack
B. HashSet
C. Queue
D. ArrayList
Solution
Step 1: Identify recursion stack tracking
During DFS, nodes in the current path are tracked to detect back edges indicating cycles.
Step 2: Choose suitable data structure
A HashSet is used to quickly check if a node is in the current recursion stack.
Final Answer:
HashSet -> Option B
Quick Check:
Use HashSet to track recursion stack nodes [OK]
Hint: Use HashSet for O(1) check if node is in recursion stack [OK]
Common Mistakes:
Using Queue which is FIFO, not suitable here
Using Stack but not checking membership efficiently
Using ArrayList which is slower for membership check
3. What will be the output of the following Java code snippet detecting cycle in a directed graph?
import java.util.*;
public class GraphCycle {
private final int V = 3;
private final List adj = new ArrayList<>();
private final boolean[] visited = new boolean[V];
private final boolean[] recStack = new boolean[V];
public GraphCycle() {
for (int i = 0; i < V; i++) adj.add(new ArrayList<>());
adj.get(0).add(1);
adj.get(1).add(2);
adj.get(2).add(0);
}
private boolean dfs(int node) {
if (recStack[node]) return true;
if (visited[node]) return false;
visited[node] = true;
recStack[node] = true;
for (int neighbor : adj.get(node)) {
if (dfs(neighbor)) return true;
}
recStack[node] = false;
return false;
}
public boolean hasCycle() {
for (int i = 0; i < V; i++) {
if (dfs(i)) return true;
}
return false;
}
public static void main(String[] args) {
GraphCycle graph = new GraphCycle();
System.out.println(graph.hasCycle());
}
}
medium
A. true
B. false
C. Compilation error
D. Runtime exception
Solution
Step 1: Analyze graph edges
Edges: 0->1, 1->2, 2->0 form a cycle (0->1->2->0).
Step 2: Trace DFS cycle detection
DFS from node 0 visits 1, then 2, then back to 0 which is in recursion stack, so returns true.
Final Answer:
true -> Option A
Quick Check:
Cycle exists in graph = true [OK]
Hint: Cycle if DFS revisits node in recursion stack [OK]
Common Mistakes:
Ignoring recursion stack check
Assuming no cycle because visited[] is true
Confusing visited[] and recStack[] roles
4. Identify the bug in this cycle detection code snippet for a directed graph: