-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Detect cycle in a directed graph.java
61 lines (47 loc) · 1.62 KB
/
GFG Detect cycle in a directed graph.java
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
53
54
55
56
57
58
59
60
// DFS Approach
class Solution {
// Function to detect cycle in a directed graph.
public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {
// code here
boolean[] vis = new boolean[V];
boolean[] dfsVis = new boolean[V];
for (int i = 0; i < V; i++)
if (!vis[i])
if (dfs(i, adj, vis, dfsVis)) return true;
return false;
}
private boolean dfs(int cur, ArrayList<ArrayList<Integer>> adj, boolean[] vis, boolean[] curVis) {
if (curVis[cur]) return true;
if (vis[cur]) return false;
vis[cur] = curVis[cur] = true;
for (int neighbor: adj.get(cur))
if (dfs(neighbor, adj, vis, curVis)) return true;
curVis[cur] = false;
return false;
}
}
// BFS Approach (Kahn's Algo)
class Solution {
// Function to detect cycle in a directed graph.
public boolean isCyclic(int V, ArrayList<ArrayList<Integer>> adj) {
// code here
int[] indegree = new int[V];
for (ArrayList<Integer> li: adj)
for (int i: li)
indegree[i]++;
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < V; i++)
if (indegree[i] == 0)
q.offer(i);
while (!q.isEmpty()) {
int cur = q.poll();
for (int n: adj.get(cur))
if (--indegree[n] == 0)
q.offer(n);
}
for (int i: indegree)
if (i != 0)
return true;
return false;
}
}