When you perform the DFS
record which is the node you came from when you visited each node. Call this parent
for the new node. Now when you reach an edge (u, v)
that leads to an already visited node v
, walk up the path made by the parents up to u
, or up to the source of the DFS
(denote this s
).
You will always reach one of the two. If you reach s
, than perform the same from v
and you have your cycle - the path from u
to s
the path from s
to v
and the new edge. If you reach v
you again have a cycle - the path from u
to v
and than the new edge.