Given a connected undirected graph, check if it contains any cycle or not.

For example, the following graph contains a cycle 2–5–10–6–2:

Cyclic breadth first tree

Practice this problem

Recommended Read:

Types of edges involved in DFS and relation between them

1. Using BFS

When we do a Breadth–first search (BFS) from any vertex v in an undirected graph, we may encounter a cross-edge that points to a previously discovered vertex that is neither an ancestor nor a descendant of the current vertex. Each “cross edge” defines a cycle in an undirected graph. If the cross edge is x —> y, then since y is already discovered, we have a path from v to y (or from y to v since the graph is undirected), where v is the starting vertex of BFS. So, we can say that we have a path v ~~ x ~ y ~~ v that forms a cycle. (Here, ~~ represents one more edge in the path, and ~ represents a direct edge).

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The graph contains a cycle

Java


Download  Run Code

Output:

The graph contains a cycle

Python


Download  Run Code

Output:

The graph contains a cycle

2. Using DFS

The following graph contains a cycle 8—9—11—12—8:

Cycle depth first tree

 
When we do a Depth–first search (DFS) from any vertex v in an undirected graph, we may encounter a back-edge that points to one of the ancestors of the current vertex v in the DFS tree. Each “back edge” defines a cycle in an undirected graph. If the back edge is x —> y, then since y is the ancestor of node x, we have a path from y to x. So, we can say that we have a path y ~~ x ~ y that forms a cycle. (Here, ~~ represents one more edge in the path, and ~ represents a direct edge).

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

The graph contains a cycle

Java


Download  Run Code

Output:

The graph contains a cycle

Python


Download  Run Code

Output:

The graph contains a cycle

The time complexity of the above solutions is O(V + E), where V and E are the total number of vertices and edges in the graph, respectively.