forked from ShyrenMore/InterviewPrep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_cycle_directed_bfs.cpp
41 lines (35 loc) · 959 Bytes
/
check_cycle_directed_bfs.cpp
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
#include <bits/stdc++.h>
using namespace std;
// https://practice.geeksforgeeks.org/problems/detect-cycle-in-a-directed-graph/
// https://youtu.be/iTBaI90lpDQ
class Solution{
public:
// Function to detect cycle in a directed graph.
bool isCyclic(int V, vector<int> adj[])
{
vector<int> indegree(V, 0);
for (int i = 0; i < V; i++){
for(auto it: adj[i])
indegree[it]++;
}
queue<int> q;
for (int i = 0; i < V; i++)
if(indegree[i] == 0)
q.push(i);
vector<int> order;
while(!q.empty())
{
int node = q.front();
q.pop();
order.push_back(node);
for(auto it: adj[node]){
indegree[it]--;
if(indegree[it] == 0)
q.push(it);
}
}
if(order.size() == V)
return false;
return true;
}
};