Graph Theory37 sections · 1633 units
Open in Course

Cycle Detection

Application 1

How do you check for a cycle in an undirected graph? Iterate through every edge (u,v)(u, v). Before adding the edge, check: are uu and vv already in the same component?

If yes, adding this edge creates a cycle. If no, union them and continue.

for each edge (u, v)
    if find(u) = find(v) then
        cycle detected
    else
        union(u, v)

This is faster than DFS-based cycle detection when you process edges one by one.