📖 Scenario: Imagine you are working with a network of friends where each friendship is a connection between two people. You want to find out if there is any circle of friends where you can start from one person and come back to the same person by following friendships without repeating any connection.
🎯 Goal: You will build a program that detects if there is a cycle (a circle) in an undirected graph representing friendships.
📋 What You'll Learn
Create a graph using an adjacency list representation with exact edges
Add a helper variable to track visited nodes
Implement a depth-first search (DFS) function to detect cycles
Print whether the graph contains a cycle or not
💡 Why This Matters
🌍 Real World
Cycle detection is important in network design, social networks, and detecting deadlocks in operating systems.
💼 Career
Understanding graph traversal and cycle detection is essential for software engineers working with complex data structures, network analysis, and algorithm optimization.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a dictionary called graph representing an undirected graph with these exact edges: 1 connected to 2 and 3, 2 connected to 1 and 3, 3 connected to 1, 2, and 4, 4 connected to 3.
DSA C#
Hint
Use a Dictionary<int, List<int>> to represent the graph. Each key is a node, and the value is a list of connected nodes.
2
Create a visited set to track visited nodes
Create a HashSet<int> called visited to keep track of nodes that have been visited during traversal.
DSA C#
Hint
Use HashSet<int> to store visited nodes for quick lookup.
3
Implement DFS function to detect cycles
Write a function called HasCycle that takes parameters int node, int parent, and uses graph and visited to detect if there is a cycle starting from node. Use depth-first search and return true if a cycle is found, otherwise false.
DSA C#
Hint
Use recursion to visit neighbors. If a neighbor is visited and is not the parent, a cycle exists.
4
Check all nodes and print if cycle exists
Use a foreach loop to check each node in graph.Keys. If a node is not in visited, call HasCycle with parent as -1. Print "Cycle detected" if any call returns true, otherwise print "No cycle detected".
DSA C#
Hint
Loop through all nodes to ensure disconnected parts are checked. Print the result based on cycle detection.
Practice
(1/5)
1. What is the main idea behind detecting a cycle in an undirected graph using DFS?
easy
A. If we visit a node that is already visited and is not the parent, a cycle exists.
B. If all nodes are visited exactly once, there is a cycle.
C. If the graph has more edges than nodes, it must have a cycle.
D. If the graph is disconnected, it contains a cycle.
Solution
Step 1: Understand DFS traversal in undirected graph
DFS visits nodes and keeps track of the parent node to avoid false cycle detection.
Step 2: Detect cycle condition
If during DFS, a visited node is found that is not the parent of the current node, it means a cycle exists.
Final Answer:
If we visit a node that is already visited and is not the parent, a cycle exists. -> Option A
Quick Check:
Cycle detection in undirected graph = check visited node not parent [OK]
Hint: Check visited nodes excluding parent during DFS [OK]
Common Mistakes:
Ignoring parent node in cycle check
Assuming disconnected graph always has cycle
Confusing cycle detection with edge count
2. Which of the following C# code snippets correctly initializes an adjacency list for an undirected graph with 3 nodes?
easy
A. var graph = new List<int>[3]; for(int i=0; i<3; i++) graph[i] = new List<int>();
B. var graph = new List<int>[3]; graph = new List<int>();
C. List<int> graph = new List<int>[3];
D. var graph = new List(); graph.Add(new List<int>());
Solution
Step 1: Understand adjacency list initialization
We need an array of lists, each list initialized separately to hold neighbors.
Step 2: Check code correctness
var graph = new List<int>[3]; for(int i=0; i<3; i++) graph[i] = new List<int>(); creates an array of List<int> and initializes each element with a new List<int>, which is correct.
Final Answer:
var graph = new List<int>[3]; for(int i=0; i<3; i++) graph[i] = new List<int>(); -> Option A
Quick Check:
Initialize array of lists with loop [OK]
Hint: Initialize each list in array separately [OK]
Common Mistakes:
Not initializing each list element
Using wrong data types for adjacency list
Assigning list directly to array variable
3. Consider the following C# code snippet for cycle detection in an undirected graph: