// pseudocode
class DirectedCycle {
boolean[] marked;
int[] edgeTo;
Stack<Integer> cycle;
boolean[] onStack; // 用于检测当前节点是不是已经处于递归栈中
cons : (DiGraph G) {
// init marked, edgeTo, onStack with size G.V()
for(int v=0; v<G.V(); v++) {
if(!marked[v]) dfs(G, v);
}
}
dfs(DiGraph G, int v) {
onStack[v] = true;
marked[v] = true;
while(int w : G.adj(v)) {
if(this.hasCycle()) return;
else if(!marked[w]) {
edgeTo[w] = v;
dfs(G, w);
}
else if(onStack[w]) {
for(int x = v; x != w; x = edgeTo[x])
cycle.push(x);
cycle.push(w);
cycle.push(v);
}
}
onStack[v] = false;
}
boolean hasCycle() {
return cycle != null;
}
Iterable<Integer> cycle() {
return cycle;
}
}
转载于:https://www.cnblogs.com/crazyRanZhang/p/8483120.html