fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. int N;
  14. List<List<Integer>> adj;
  15. Scanner input = new Scanner(System.in);
  16. N = input.nextInt();
  17. adj = new ArrayList<>();
  18. adj.add(Arrays.asList(1));
  19. adj.add(Arrays.asList(2,5));
  20. adj.add(Arrays.asList(3));
  21. adj.add(Arrays.asList(4));
  22. adj.add(Arrays.asList(1));
  23. adj.add(new ArrayList<>());
  24.  
  25. // adj.add(Arrays.asList(3, 4));
  26. // adj.add(Arrays.asList(4, 1));
  27. System.out.println(isCyclic(N,adj));
  28.  
  29. }
  30. public static boolean dfs(int i, int []vis,int [] path,List<List<Integer>> adj){
  31. vis[i]=1;
  32. path[i]=1;
  33. for(int it : adj.get(i)){
  34. if(vis[it]==0){
  35. if(dfs(it,vis,path,adj)){
  36. return true;
  37. }
  38. }
  39. else if(path[it]==1){
  40. return true;
  41. }
  42. }
  43. path[i]=0;
  44. return false;
  45. }
  46. public static boolean isCyclic(int N, List<List<Integer>> adj) {
  47. int [] vis = new int [N];
  48. int [] path = new int [N];
  49. //path.resize(N+1);
  50. for(int i=0;i<N;i++){
  51. if(dfs(i,vis,path,adj)){
  52. return true;
  53. }
  54. }
  55. return false;
  56. }
  57.  
  58. }
  59.  
  60.  
Success #stdin #stdout 0.11s 56684KB
stdin
6
stdout
true