forked from akkupy/codeDump
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedGraphCycleDetectionBFS.cpp
More file actions
43 lines (32 loc) · 956 Bytes
/
Copy pathDirectedGraphCycleDetectionBFS.cpp
File metadata and controls
43 lines (32 loc) · 956 Bytes
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
// https://www.codingninjas.com/codestudio/problems/detect-cycle-in-a-directed-graph_1062626?leftPanelTab=1&utm_source=youtube&utm_medium=affiliate&utm_campaign=Lovebabbar
#include<unordered_map>
#include<queue>
#include<list>
int detectCycleInDirectedGraph(int n, vector < pair < int, int >> & edges) {
unordered_map<int, list<int>> adj;
for(auto i : edges){
adj[i.first].push_back(i.second);
}
vector<int> inDegree(n+1,0);
for(auto i : adj){
for(auto j : i.second)
inDegree[j]++;
}
queue<int> q;
for(int i=1; i<=n; i++){
if(inDegree[i]==0)
q.push(i);
}
int count= 0;
while(!q.empty()){
int front= q.front();
q.pop();
count++;
for(auto i : adj[front]){
inDegree[i]--;
if(inDegree[i]==0)
q.push(i);
}
}
return count!=n;
}