The existence of a cycle in directed and undirected graphs can be determined by whether a
depth-first search (DFS) finds an edge that points to an ancestor of the current vertex (i.e., it contains a
back edge). All the back edges which DFS skips over are part of cycles. In an undirected graph, the edge to the parent of a node should not be counted as a back edge, but finding any other already visited vertex will indicate a back edge. In the case of undirected graphs, only
O(
n) time is required to find a cycle in an
n-vertex graph, since at most
n − 1 edges can be tree edges. Many
topological sorting algorithms will detect cycles too, since those are obstacles for topological order to exist. Also, if a directed graph has been divided into
strongly connected components, cycles only exist within the components and not between them, since cycles are strongly connected.
Algorithm The aforementioned use of depth-first search to find a cycle can be described as follows: For every vertex v: visited(v) = finished(v) = false For every vertex v: DFS(v) where DFS(v) = if finished(v): return if visited(v): "Cycle found" return visited(v) = true for every neighbour w: DFS(w) finished(v) = true For undirected graphs, "neighbour" means all vertices connected to
v, except for the one that recursively called
DFS(v). This omission prevents the algorithm from finding a trivial cycle of the form
v→
w→
v; these exist in every undirected graph with at least one edge. A variant using
breadth-first search instead will find a cycle of the smallest possible length. == Covering graphs by cycle ==