class Vertex { // for all i in [0..next.length-1] // there is an edge from `this` to `next[i]` Vertex[] next; int mark; static bool HasCycle(Vertex[] vertices) { bool Inner(Vertex v) { if (v.mark == 1) return true; v.mark = 1; foreach (var n in v.next) if (Inner(n)) return true; v.mark = 0; return false; } try { foreach (var v in vertices) if (Inner(v)) return true; } finally { foreach (var v in vertices) v.mark = 0; //clear marks for purity } return false; } }