Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create detect cycle in dfs #76

Merged
merged 1 commit into from
Oct 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions detect cycle in dfs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.ArrayList;
import java.util.List;

public class Graph {
private final int V;
private final List<List<Integer>> adj;

public Graph(int V) {
this.V = V;
adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
}

public void addEdge(int v, int w) {
adj.get(v).add(w);
adj.get(w).add(v); // Since the graph is undirected
}

private boolean isCyclicUtil(int v, boolean[] visited, int parent) {
visited[v] = true;
for (Integer i : adj.get(v)) {
if (!visited[i]) {
if (isCyclicUtil(i, visited, v)) {
return true;
}
} else if (i != parent) {
return true;
}
}
return false;
}

public boolean isCyclic() {
boolean[] visited = new boolean[V];
for (int i = 0; i < V; i++) {
if (!visited[i]) {
if (isCyclicUtil(i, visited, -1)) {
return true;
}
}
}
return false;
}

public static void main(String[] args) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 0);

if (g.isCyclic()) {
System.out.println("Cycle detected");
} else {
System.out.println("No cycle detected");
}
}
}