void DFS(Digraph g, int s) { marked[s] = true; onStack[s] = true; foreach (int v in g.AdjList(s)) { if (hasCycle) { return; } if (!marked[v]) { edgeTo[v] = s; DFS(g, v); } else { if (onStack[v]) // this means, we hit v agin in a cycle { hasCycle = true; stackCycle = new Stack <int>(); for (int x = s; x != v; x = edgeTo[x])//starting from the parent of the current node, until it hits the current node { stackCycle.Push(x); } stackCycle.Push(v); // push the current node stackCycle.Push(s); // push the parent node of the current again to for the loop } } } onStack[s] = false; }
public void DFS(Digraph g, int s) { isMarked[s] = true; id[s] = count; Console.Write(s + ", "); foreach (int v in g.AdjList(s)) { if (!isMarked[v]) { DFS(g, v); } } }
void DFS(Digraph g, int source) { isMarked[source] = false; preOrder.Enqueue(source); foreach (int v in g.AdjList(source)) { if (!isMarked[v]) { DFS(g, v); } } postOrder.Enqueue(source); postReverseOrder.Push(source); }