-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDetectCycleInUndirectedGraph.cpp
More file actions
52 lines (49 loc) · 1.11 KB
/
Copy pathDetectCycleInUndirectedGraph.cpp
File metadata and controls
52 lines (49 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* GFG Tested
Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not
*/
//using dfs
class Solution {
public:
void DFS(int *visited,vector<int> adj[],int i,int *parent,bool &ans)
{
visited[i]=1;
for(auto it=adj[i].begin();it!=adj[i].end();it++)
{
if(visited[*it]!=1)
{
parent[*it]=i;
DFS(visited,adj,*it,parent,ans);
}
else
{
if(parent[i]!=*it)
{
ans=true;
return;
}
}
}
}
bool isCycle(int V, vector<int>adj[]){
int *parent=(int *)malloc(V*sizeof(int));
int *visited=(int *)malloc(V*sizeof(int));
for(int i=0;i<V;i++)
{
parent[i]=-1;
visited[i]=0;
}
bool ans=false;
for(int i=0;i<V;i++)
{
if(visited[i]==0)
{
DFS(visited,adj,i,parent,ans);
}
if(ans==true)
break;
}
free(visited);
free(parent);
return ans;
}
};