import java.util.*; import java.io.*; class CycleDetectionDirectedGraphDFS { // DFS public static boolean dfsCheck(int node, boolean visited[], boolean pathVis[], ArrayList> adj){ visited[node] = true; pathVis[node] = true; for(int next : adj.get(node)){ if(!visited[next]){ if(dfsCheck(next, visited, pathVis, adj)) return true; } else if(pathVis[next]){ return true; } } pathVis[node] = false; return false; } public static boolean isCyclic(int V, ArrayList> adj){ boolean visited[] = new boolean[V]; boolean pathVis[] = new boolean[V]; for(int i=0;i> makeGraph(int V){ ArrayList> adj = new ArrayList<>(); for(int i=0;i()); return adj; } // DRIVER public static void main(String args[]){ // ================= CASE 1 ================= { int V = 6; ArrayList> adj = makeGraph(V); /* 0 → 1 → 2 → 3 ↑ ↓ └─────┘ 4 → 5 */ adj.get(0).add(1); adj.get(1).add(2); adj.get(2).add(3); adj.get(3).add(1); adj.get(4).add(5); System.out.printf("Case 1: %s\n", isCyclic(V, adj) ? "Cycle detected" : "No cycle"); } // ================= CASE 2 ================= { int V = 4; ArrayList> adj = makeGraph(V); /* 0 → 1 → 2 → 3 No cycle */ adj.get(0).add(1); adj.get(1).add(2); adj.get(2).add(3); System.out.printf("Case 2: %s\n", isCyclic(V, adj) ? "Cycle detected" : "No cycle"); } // ================= CASE 3 ================= { int V = 3; ArrayList> adj = makeGraph(V); /* 0 → 1 1 → 2 2 → 0 */ adj.get(0).add(1); adj.get(1).add(2); adj.get(2).add(0); System.out.printf("Case 3: %s\n", isCyclic(V, adj) ? "Cycle detected" : "No cycle"); } // ================= CASE 4 ================= { int V = 5; ArrayList> adj = makeGraph(V); /* disconnected, no cycle 0 → 1 2 → 3 4 alone */ adj.get(0).add(1); adj.get(2).add(3); System.out.printf("Case 4: %s\n", isCyclic(V, adj) ? "Cycle detected" : "No cycle"); } } }