Skip to content

Instantly share code, notes, and snippets.

@rohithpeddi
Last active November 10, 2016 15:55
Show Gist options
  • Save rohithpeddi/0d6b9c5067e3f5d09ee6b254caa43944 to your computer and use it in GitHub Desktop.
Save rohithpeddi/0d6b9c5067e3f5d09ee6b254caa43944 to your computer and use it in GitHub Desktop.
Detects a Cycle in a graph
static class CycleDetector {
ArrayList<ArrayList<Edge>> adj;
boolean[] marked;
boolean hasCycle = false;
public CycleDetector(ArrayList<ArrayList<Edge>> adj) {
this.adj = adj;
marked = new boolean[adj.size()];
for (int i = 1; i < adj.size(); i++) {
if (!marked[i]) {
dfs(-1, i);
}
}
}
public void dfs(int u, int v) {
if (hasCycle) {
return;
}
marked[v] = true;
for (Edge e : adj.get(v)) {
int w = e.otherVertex(v);
if (!marked[w]) {
dfs(v, w);
} else if (w != u) {
hasCycle = true;
}
}
}
}
static class Edge implements Comparable<Edge> {
int u;
int v;
int weight;
public Edge(int u, int v, int weight) {
this.u = u;
this.v = v;
this.weight = weight;
}
public int compareTo(Edge that) {
return Integer.compare(this.weight, that.weight);
}
public int eitherVertex() {
return u;
}
public int otherVertex(int x) {
return x == v ? u : v;
}
public int getWeight() {
return weight;
}
public String toString() {
return "( " + u + " -- " + v + ", " + weight + " )";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment