Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- // Function to detect cycle in an undirected graph.
- vector<bool> visited;
- bool dfs(int node, int parent, vector<int> adj[]) {
- visited[node] = true;
- for(int neigh : adj[node]) {
- if(!visited[neigh] ) {
- if(dfs(neigh, node, adj))
- return true;
- }
- else if(neigh != parent) {
- return true;
- }
- }
- return false;
- }
- bool isCycle(int V, vector<int> adj[]) {
- visited = vector<bool>(V + 1, false);
- for(int i = 1; i <= V; i++) {
- if(!visited[i]) {
- if(dfs(i, 0, adj)) {
- return true;
- }
- }
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement