1. class Solution {
  2. public boolean isCyclic(int V, int[][] edges) {
  3. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  4.  
  5. for(int i=0; i<V; i++)
  6. {
  7. adj.add(new ArrayList<Integer>());
  8. }
  9.  
  10. for(int [] edge : edges)
  11. {
  12. int u = edge[0];
  13. int v = edge[1];
  14. adj.get(u).add(v);
  15. }
  16.  
  17. // to keep a track of nodes if they are visited or not
  18. boolean[] visited = new boolean[V];
  19. // to keep a track of nodes if they are visited in same path or not
  20. boolean[] pathVisited = new boolean[V];
  21.  
  22. for(int i=0; i<V; i++)
  23. {
  24. if(visited[i] == false)
  25. {
  26. if(dfs(adj, visited, pathVisited, i))
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32.  
  33. public boolean dfs(ArrayList<ArrayList<Integer>> adj, boolean[] visited, boolean[] pathVisited, int node)
  34. {
  35. visited[node] = true;
  36. pathVisited[node] = true;
  37.  
  38. // traverse through neighbours
  39. for(int v : adj.get(node))
  40. {
  41. if(visited[v] == false)
  42. {
  43. if(dfs(adj, visited, pathVisited, v))
  44. return true;
  45. }
  46. // if neighbour node is visited already in same path earlier, then it creates a cycle now
  47. else if(pathVisited[v] == true)
  48. return true;
  49. }
  50. // unmark the current node from pathVisited array because we are going to check another path now
  51. pathVisited[node] = false;
  52. return false;
  53. }
  54. }