Summary of "G-12. Detect a Cycle in an Undirected Graph using DFS | C++ | Java"

Detecting a cycle in an undirected graph using DFS

Main idea

Detailed algorithm (pseudocode-style)

  1. Data structures

    • visited[]: boolean array initialized to false for all nodes.
    • adjacency list representation of the graph.
    • DFS function signature: dfs(node, parent)
  2. DFS function (returns boolean: true if a cycle is found in this call/subtree)

    • visited[node] = true
    • For each neighbor v in adjacency[node]:
      • If visited[v] == false:
        • If dfs(v, node) returns true, immediately return true
      • Else (visited[v] == true):
        • If v != parent, then return true (visited non-parent neighbor ⇒ cycle)
    • After exploring all neighbors, return false (no cycle found from this node)
  3. Main driver (handles multiple components)

    • For every node i in 1..N (or 0..N-1 for 0-based indexing):
      • If visited[i] == false:
        • If dfs(i, -1) returns true, then there exists a cycle (stop and report)
    • If none of the DFS calls returned true, report no cycle

Key check: if a visited neighbor is not the parent, that indicates a cycle.

Example traversal (illustrative)

Key implementation details / reminders

Complexity

Coding notes

References mentioned

Speakers / sources

Category ?

Educational


Share this summary


Is the summary off?

If you think the summary is inaccurate, you can reprocess it with the latest model.

Video