-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDetectCyscleInDirectedGraph.cpp
More file actions
49 lines (46 loc) · 1.01 KB
/
Copy pathDetectCyscleInDirectedGraph.cpp
File metadata and controls
49 lines (46 loc) · 1.01 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
/* GFG Tested
Given a Directed Graph with V vertices and E edges, check whether it contains any cycle or not.
*/
//topological sort
class Solution {
public:
bool isCyclic(int V, vector<int> adj[]) {
int *indegree=(int *)calloc(V,sizeof(int));
queue<int> q;
for(int i=0;i<V;i++)
{
for(auto it=adj[i].begin();it!=adj[i].end();it++)
{
indegree[*it]++;
}
}
/*for(int i=0;i<V;i++)
cout<<indegree[i]<<endl;*/
int visited=0;
for(int i=0;i<V;i++)
{
if(indegree[i]==0)
{
visited++;
q.push(i);
}
}
while(!q.empty())
{
int temp=q.front();
q.pop();
for(auto it=adj[temp].begin();it!=adj[temp].end();it++)
{
indegree[*it]--;
if(indegree[*it]==0)
{
visited++;
q.push(*it);
}
}
}
if(visited==V)
return false;
return true;
}
};