# Python Program to Find if Undirected Graph contains Cycle using BFS

PythonServer Side ProgrammingProgramming

When it is required to find the sum of all the nodes of a tree, a class is created, and it contains methods to set the root node, add elements to the tree, search for a specific element, and add elements of the tree to find the sum and so on. An instance of the class can be created to access and use these methods.

Below is a demonstration of the same −

## Example

Live Demo

from collections import deque

def detect_cycle(adj: list, s, V, visited: list):

parent = [-1] * V

q = deque()

visited[s] = True
q.append(s)

while q != []:

u = q.pop()

if not visited[v]:
visited[v] = True
q.append(v)
parent[v] = u
elif parent[u] != v:
return True
return False

visited = [False] * V

for i in range(V):
if not visited[i] and detect_cycle(adj, i, V, visited):
return True
return False

if __name__ == "__main__":
V = 5
adj = [[] for i in range(V)]

print("There are 5 vertices in the graph")
print("0-->1")
print("1-->2")
print("2-->0")
print("2-->3")
print("2-->1")
print("Is there a cycle ?")
print("Yes")
else:
print("There are 5 vertices in the graph")
print("0-->1")
print("1-->2")
print("2-->0")
print("2-->3")
print("2-->1")
print("Is there a cycle ?")
print("Yes")
print("No")

## Output

There are 5 vertices in the graph
0-->1
1-->2
2-->0
2-->3
2-->1
Is there a cycle ?
Yes

## Explanation

• The required packages are imported.

• Another method named ‘add_edge’ is defined that helps add nodes to the graph.

• A method named ‘detect_cycle’ is defined that helps determine if a cycle is formed when the components of the graph are connected.

• Another method named ‘cycle_disconnected’ is defined that helps determine if the cycle is a connected one or not.