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

Main idea / concept

In an undirected graph, two different BFS paths reaching the same node (at the same or different levels) where the previously visited node is not the immediate parent indicates a cycle.


Detailed methodology (step-by-step algorithm)

  1. Data structures

    • Adjacency list for the graph.
    • visited array of size V, initialized to false.
    • Queue that stores pairs (node, parent) so each queued node remembers which node it came from.
  2. Handle disconnected graphs

    • Loop over all vertices (e.g., 0..n-1 or 1..n depending on indexing).
    • If vertex i is not visited, call detectCycle(i).
  3. BFS-based detectCycle(source)

    • Mark visited[source] = true.
    • Enqueue (source, parent = -1) into the queue.
    • While the queue is not empty:
      • Dequeue (node, parent).
      • For each neighbor adj of node:
        • If adj is not visited:
          • Mark visited[adj] = true.
          • Enqueue (adj, parent = node).
        • Else (if adj is already visited):
          • If adj != parent: return true (cycle found).
          • If adj == parent: ignore (edge back to parent).
    • If BFS finishes without finding such a visited-but-not-parent neighbor, return false (no cycle in this component).
  4. Final decision

    • If any component’s detectCycle returns true, the graph has a cycle.
    • If none return true after checking all components, the graph is acyclic.

Important implementation details & tips


Intuition / example

BFS explores neighbors level by level. Two nodes explored from different branches can both reach the same subsequent node; if one branch visits it first and the other later finds it already visited and it’s not its parent, that collision indicates a cycle.

Example (from the video): nodes 5 and 6 both reach node 7 — this collision signals a cycle.


Complexity


Other notes


Speakers / sources featured

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