Given an undirected graph with V
vertices labelled from 0
to V-1
and E
edges, check whether the graph contains any cycle or not. The Graph is represented as an adjacency list, where adj[i]
contains all the vertices that are directly connected to vertex i
.
NOTE: The adjacency list represents undirected edges, meaning that if there is an edge between vertex i
and vertex j
, both j
will be adj[i]
and i
will be in adj[j]
.
-
Graph Representation:
- The graph is represented using an adjacency list, where each vertex
i
is connected to all vertices inadj[i]
.
- The graph is represented using an adjacency list, where each vertex
-
Cycle Detection using BFS:
- Use Breadth First Search (BFS) to traverse the graph.
- Maintain a
visited
vector to track whether a vertex has been visited. - Use a queue to store pairs of vertices and their parents. Each pair consists of the current vertex and the vertex from which it was discovered.
-
Algorithm:
- For each vertex
i
from0
ton-1
, if it is not visited, perform the following:- Initialize a BFS queue and push the starting vertex
i
with a parent of-1
. - While the queue is not empty:
- Dequeue the front element, marking the current vertex as visited.
- For each neighbor of the current vertex:
- If the neighbor is already visited and is not the parent of the current vertex, a cycle is detected.
- If the neighbor is not visited, add it to the queue with the current vertex as its parent.
- Initialize a BFS queue and push the starting vertex
- For each vertex
-
Return:
- If any cycle is detected during the BFS traversal, return
true
. - If no cycles are detected, return
false
.
- If any cycle is detected during the BFS traversal, return
- Compile:
g++ -o solution solution.cpp
- Run:
./solution
If you have any questions, suggestions, or feedback, feel free to reach out to me:
- GitHub: satendra03
- Email: satendrakumarparteti.work@gmail.com
Happy coding! 😊