The idea is to use BFS to detect a cycle in an undirected graph. We start BFS for all components of the graph and check if a node has been visited earlier, ensuring that we do not consider the parent node of the current node while making this check. If we encounter a visited node that is not the parent, a cycle exists in the graph. Otherwise, we continue BFS by marking the node as visited and inserting it into the queue.
Step by step approach:
Initialize a visited array of size n (number of nodes) to false.
Iterate through all nodes from 0 to n-1. If a node is not visited, start BFS.
Push the node into the queue with its parent set to -1.
Perform BFS:
Pop a node from the queue.
Traverse all its adjacent nodes.
If an adjacent node is visited and is not the parent, return true (cycle detected).
Otherwise, if the adjacent node is not visited, mark it as visited and push it into the queue with the current node as its parent.
If no cycle is found after checking all components, return false.
Implementation:
Output
true
Time Complexity:O(V+E), It visits each node once and processes each edge once using an adjacency list. Space Complexity: O(V), O(V) for the queue and visited array.
We do not count the adjacency list in auxiliary space as it is necessary for representing the input graph.