Bird
Raised Fist0
DSA C++programming~10 mins

Cycle Detection in Undirected Graph in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Cycle Detection in Undirected Graph
Start at any node
↓
Mark node as visited
↓
For each neighbor
↓
If neighbor not visited
↓
Recurse DFS
↓
Cycle found
↓
Return result
Start DFS from any node, mark visited, explore neighbors. If a visited neighbor is not the parent, a cycle exists.
Execution Sample
DSA C++
void dfs(int node, int parent) {
  visited[node] = true;
  for (auto nbr : graph[node]) {
    if (!visited[nbr]) dfs(nbr, node);
    else if (nbr != parent) cycle = true;
  }
}
DFS visits nodes, marks them, and checks for back edges indicating cycles.
Execution Table
StepOperationNode VisitedParentVisited SetCycle DetectedVisual State
1Start DFS0-1[0]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
2Visit neighbor 110[0,1]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
3Neighbor 1 has no unvisited neighbors--[0,1]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
4Back to node 0, visit neighbor 220[0,1,2]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
5Visit neighbor 3 from 232[0,1,2,3]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
6Neighbor 3 has neighbor 2 (parent), no cycle--[0,1,2,3]False0 -> [1,2] 1 -> [0] 2 -> [3] 3 -> [2,0]
7At node 3, check neighbor 0 (visited, not parent)03[0,1,2,3]TrueCycle detected via edge 3-0
8Cycle found, stop DFS--[0,1,2,3]TrueCycle detected
9End--[0,1,2,3]TrueFinal state with cycle
💡 Cycle detected when visiting a visited neighbor that is not the parent.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4After Step 5After Step 7Final
visited[][0][0,1][0,1,2][0,1,2,3][0,1,2,3][0,1,2,3]
cycleFalseFalseFalseFalseFalseTrueTrue
current_node-01233-
parent_node--10023-
Key Moments - 3 Insights
Why do we check if the visited neighbor is not the parent to detect a cycle?
Because in an undirected graph, the edge back to the parent is normal traversal, not a cycle. The cycle is detected only if a visited neighbor is different from the parent (see execution_table step 7).
What happens if the graph is disconnected?
We run DFS from each unvisited node to cover all components. Cycle detection applies to each component separately.
Why do we mark nodes as visited before exploring neighbors?
Marking visited early prevents revisiting the same node and infinite loops. This is shown in execution_table step 1 where node 0 is marked visited before neighbors are checked.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, which node is currently visited and what is its parent?
ANode 3, parent 2
BNode 2, parent 0
CNode 1, parent 0
DNode 0, parent -1
💡 Hint
Check the 'Node Visited' and 'Parent' columns at step 5 in execution_table.
At which step does the cycle get detected according to the execution_table?
AStep 4
BStep 3
CStep 7
DStep 9
💡 Hint
Look at the 'Cycle Detected' column in execution_table to find when it changes to True.
If the graph had no back edge to a visited node other than the parent, what would be the final value of 'cycle'?
ATrue
BFalse
CUndefined
DDepends on starting node
💡 Hint
Refer to variable_tracker row for 'cycle' and see when it changes from False to True.
Concept Snapshot
Cycle Detection in Undirected Graph using DFS:
- Start DFS from any node, mark visited.
- For each neighbor:
  - If not visited, recurse DFS.
  - If visited and not parent, cycle found.
- Cycle means a back edge exists.
- Works for disconnected graphs by checking all nodes.
Full Transcript
Cycle detection in an undirected graph uses depth-first search (DFS). We start from any node, mark it visited, and explore neighbors. If we find a neighbor already visited and it is not the parent node, it means a cycle exists. We track visited nodes to avoid revisiting. The process repeats for all disconnected parts of the graph. The key is to distinguish between the parent edge and a back edge to detect cycles correctly.

Practice

(1/5)
1. What is the main idea behind detecting a cycle in an undirected graph using DFS?
easy
A. If all nodes are visited once, the graph has a cycle.
B. If we visit a node that is already visited and is not the parent, a cycle exists.
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

  1. Step 1: Understand DFS traversal in undirected graph

    DFS visits nodes and tracks the parent node to avoid false cycle detection.
  2. Step 2: Detect cycle condition

    If a visited node is found that is not the parent, it means a back edge exists, indicating a cycle.
  3. Final Answer:

    If we visit a node that is already visited and is not the parent, a cycle exists. -> Option B
  4. Quick Check:

    Cycle detection in undirected graph = check visited and parent [OK]
Hint: Check visited nodes excluding parent to find cycles [OK]
Common Mistakes:
  • Ignoring the parent node in cycle check
  • Assuming disconnected graph always has cycles
  • Confusing cycle detection with number of edges
2. Which of the following C++ function signatures is correct for a DFS-based cycle detection helper in an undirected graph?
easy
A. bool dfs(int node, int parent, vector& graph, vector<bool>& visited);
B. void dfs(int node, vector<int>& graph, vector<bool>& visited);
C. bool dfs(int node, vector<int>& graph, vector<int>& visited, int parent);
D. int dfs(int node, int parent, vector<int>& graph, vector<bool>& visited);

Solution

  1. Step 1: Analyze function parameters for DFS cycle detection

    We need current node, parent node, adjacency list (graph), and visited array.
  2. Step 2: Check return type and parameter types

    Return type should be bool to indicate cycle presence; graph is vector of vectors; visited is bool vector.
  3. Final Answer:

    bool dfs(int node, int parent, vector& graph, vector<bool>& visited); -> Option A
  4. Quick Check:

    Correct DFS signature includes parent and returns bool [OK]
Hint: DFS cycle helper returns bool and takes parent node [OK]
Common Mistakes:
  • Using wrong graph data type (vector<int> instead of vector)
  • Missing parent parameter
  • Wrong return type for cycle detection
3. What will be the output of the following code snippet detecting cycle in an undirected graph?
int main() {
  vector graph = {{1,2}, {0,2}, {0,1,3}, {2}};
  vector<bool> visited(4, false);
  bool hasCycle = false;
  function dfs = [&](int node, int parent) {
    visited[node] = true;
    for (int adj : graph[node]) {
      if (!visited[adj]) {
        if (dfs(adj, node)) return true;
      } else if (adj != parent) {
        return true;
      }
    }
    return false;
  };
  for (int i = 0; i < 4; i++) {
    if (!visited[i]) {
      if (dfs(i, -1)) {
        hasCycle = true;
        break;
      }
    }
  }
  cout << (hasCycle ? "Cycle Found" : "No Cycle") << endl;
  return 0;
}
medium
A. Runtime Error
B. No Cycle
C. Compilation Error
D. Cycle Found

Solution

  1. Step 1: Analyze graph structure

    Graph edges: 0-1, 0-2, 1-2, 2-3. Nodes 0,1,2 form a triangle (cycle).
  2. Step 2: Trace DFS cycle detection

    DFS visits nodes and finds back edge between 0 and 2 or 1 and 2, detecting cycle.
  3. Final Answer:

    Cycle Found -> Option D
  4. Quick Check:

    Triangle in graph means cycle detected [OK]
Hint: Triangle or more edges among nodes means cycle [OK]
Common Mistakes:
  • Ignoring back edge condition
  • Assuming no cycle if graph is connected
  • Confusing parent node with visited node
4. Identify the bug in the following cycle detection code for an undirected graph:
bool dfs(int node, int parent, vector& graph, vector<bool>& visited) {
  visited[node] = true;
  for (int adj : graph[node]) {
    if (!visited[adj]) {
      if (dfs(adj, node, graph, visited)) return true;
    } else {
      return true;
    }
  }
  return false;
}
medium
A. It returns true even if adjacent node is the parent, causing false cycle detection.
B. It does not mark nodes as visited.
C. It uses wrong data types for graph and visited.
D. It never returns false.

Solution

  1. Step 1: Review cycle detection condition

    The else block returns true if adjacent node is visited, but does not check if it is the parent.
  2. Step 2: Identify impact of missing parent check

    Returning true for parent node causes false positive cycle detection.
  3. Final Answer:

    It returns true even if adjacent node is the parent, causing false cycle detection. -> Option A
  4. Quick Check:

    Check parent node before returning true for visited adjacency [OK]
Hint: Always exclude parent node when checking visited adjacency [OK]
Common Mistakes:
  • Not checking if visited node is parent
  • Returning true too early
  • Incorrect recursion parameters
5. Given a graph with 5 nodes and edges: 0-1, 1-2, 2-3, 3-4, 4-1, which modification to the DFS cycle detection algorithm will correctly identify the cycle and also return the nodes involved in the cycle?
hard
A. Remove the parent check and mark all visited nodes as cycle nodes.
B. Use BFS instead of DFS to detect cycles and print nodes.
C. Modify DFS to store the path stack and return the cycle path when a back edge is found.
D. Count edges and nodes; if edges >= nodes, print all nodes as cycle.

Solution

  1. Step 1: Understand cycle detection with node tracking

    DFS can track the current path using a stack or vector to record nodes visited in the current recursion.
  2. Step 2: Modify DFS to return cycle path

    When a back edge is found (visited node not parent), extract nodes from the path stack to get cycle nodes.
  3. Final Answer:

    Modify DFS to store the path stack and return the cycle path when a back edge is found. -> Option C
  4. Quick Check:

    Track path in DFS to identify cycle nodes [OK]
Hint: Use path stack in DFS to retrieve cycle nodes [OK]
Common Mistakes:
  • Using BFS which doesn't track path easily
  • Ignoring parent check causing false cycles
  • Using edge count alone to identify cycle nodes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard