Cycles in an Undirected Graph

Eran Kampf picture Eran Kampf · Feb 8, 2009 · Viewed 105.9k times · Source

Given an undirected graph G=(V, E) with n vertices (|V| = n), how do you find if it contains a cycle in O(n)?

Answer

Rafał Dowgird picture Rafał Dowgird · Feb 8, 2009

I think that depth first search solves it. If an unexplored edge leads to a node visited before, then the graph contains a cycle. This condition also makes it O(n), since you can explore maximum n edges without setting it to true or being left with no unexplored edges.