mirror of https://github.com/evanferrao/dsa
137 lines
3.2 KiB
Java
137 lines
3.2 KiB
Java
import java.util.*;
|
|
import java.io.*;
|
|
|
|
class CycleDetectionDirectedGraphDFS {
|
|
|
|
// DFS
|
|
public static boolean dfsCheck(int node, boolean visited[],
|
|
boolean pathVis[],
|
|
ArrayList<ArrayList<Integer>> 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<ArrayList<Integer>> adj){
|
|
|
|
boolean visited[] = new boolean[V];
|
|
boolean pathVis[] = new boolean[V];
|
|
|
|
for(int i=0;i<V;i++){
|
|
if(!visited[i]){
|
|
if(dfsCheck(i, visited, pathVis, adj)) return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
|
|
// helper to create adjacency list
|
|
public static ArrayList<ArrayList<Integer>> makeGraph(int V){
|
|
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
|
|
for(int i=0;i<V;i++) adj.add(new ArrayList<>());
|
|
return adj;
|
|
}
|
|
|
|
|
|
// DRIVER
|
|
public static void main(String args[]){
|
|
|
|
// ================= CASE 1 =================
|
|
{
|
|
int V = 6;
|
|
ArrayList<ArrayList<Integer>> 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<ArrayList<Integer>> 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<ArrayList<Integer>> 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<ArrayList<Integer>> 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");
|
|
}
|
|
}
|
|
}
|