-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetect Cycle in directed graph using DFS
More file actions
43 lines (41 loc) · 1.16 KB
/
Copy pathDetect Cycle in directed graph using DFS
File metadata and controls
43 lines (41 loc) · 1.16 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
class Solution {
boolean dfs(int node, List<List<Integer>> adj, int[] visited, int[] currPath){
visited[node]=1;
currPath[node]=1;
//dfs traversal
for(int nbr: adj.get(node)){
if(visited[nbr]==0){
boolean ans=dfs(nbr,adj, visited, currPath);
if(ans) return true;
}
else{
if(currPath[nbr]==1){
return true;
}
}
}
currPath[node]=0;
return false;
}
public boolean isCyclic(int V, int[][] edges) {
// code here
List<List<Integer>> adj=new ArrayList<>();
for(int i=0; i<V; i++){
adj.add(new ArrayList<>());
}
int[] visited=new int[V];
int[] currPath=new int[V];
for(int[] edge: edges){
int u=edge[0];
int v=edge[1];
adj.get(u).add(v);
}
for(int i=0; i<V; i++){
if(visited[i]==0){
boolean ans=dfs(i,adj,visited,currPath);
if(ans) return true;
}
}
return false;
}
}