dsa/Graphs/CycleDetectionDFS.java

76 lines
1.7 KiB
Java

import java.util.*;
import java.io.*;
class Main {
// helper structure
static class Node{
int node;
int parent;
Node(int node, int parent){
this.node = node;
this.parent = parent;
}
}
public static boolean dfs(Node cur, boolean visited[],
ArrayList<ArrayList<Integer>> adj){
int u = cur.node;
int par = cur.parent;
visited[u] = true;
for(int v : adj.get(u)){
if(!visited[v]){
if(dfs(new Node(v, u), visited, adj)) return true;
}
else if(v != par){
return true; // cycle
}
}
return false;
}
public static boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj){
boolean visited[] = new boolean[V];
for(int i=0;i<V;i++){
if(!visited[i]){
if(dfs(new Node(i, -1), visited, adj)) return true;
}
}
return false;
}
// ================= DRIVER =================
public static void main(String args[]){
int V = 5;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<V;i++) adj.add(new ArrayList<>());
// Undirected graph
adj.get(0).add(1);
adj.get(1).add(0);
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(3).add(2);
adj.get(3).add(1);
adj.get(1).add(3);
adj.get(3).add(4);
adj.get(4).add(3);
System.out.printf(isCycle(V, adj) ? "Cycle detected\n" : "No cycle detected\n");
}
}