/// <summary> /// check that algorithm computes either the topological order or finds a directed cycle /// </summary> /// <param name="G"></param> /// <param name="v"></param> private void dfs(Digraph G, int v) { onStack[v] = true; marked[v] = true; foreach (int w in G.Adj(v)) { //short circuit if directed cycle found if (cycle != null) { return; } else if (!marked[w]) { edgeTo[w] = v; dfs(G, w); } //trace back directed cycle else if (onStack[w]) { cycle = new Stack <int>(); for (int x = v; x != w; x = edgeTo[x]) { cycle.Push(x); } cycle.Push(w); cycle.Push(v); } } onStack[v] = false; }
/// <summary> /// bfs from single source /// </summary> /// <param name="g"></param> /// <param name="s"></param> private void bfs(Digraph g, int s) { Queue <int> q = new Queue <int>(); for (int i = 0; i < g.V; i++) { distTo[i] = INFINITY; } //we can reach s distTo[s] = 0; marked[s] = true; q.Enqueue(s); while (q.Count > 0) { int v = q.Dequeue(); foreach (int w in g.Adj(v)) { if (!marked[w]) { edgeTo[w] = v; distTo[w] = distTo[v] + 1; marked[w] = true; q.Enqueue(w); } } } }
/// <summary> /// bfs from multi sources /// </summary> /// <param name="g"></param> /// <param name="sources"></param> private void bfs(Digraph g, IEnumerable <int> sources) { Queue <int> q = new Queue <int>(); foreach (int s in sources) { marked[s] = true; distTo[s] = 0; q.Enqueue(s); } while (q.Count > 0) { int v = q.Dequeue(); foreach (int w in g.Adj(v)) { if (!marked[w]) { edgeTo[w] = v; distTo[w] = distTo[v] + 1; marked[w] = true; q.Enqueue(w); } } } }
private void dfs(Digraph g, int v) { marked[v] = true; foreach (int w in g.Adj(v)) { if (!marked[w]) { dfs(g, w); } } }
/// <summary> /// depth first search /// </summary> /// <param name="g"></param> /// <param name="v"></param> private void dfs(Digraph g, int v) { //before this run, marked[v] always false marked[v] = true; count++; connected.Add(v); foreach (int w in g.Adj(v)) { if (!marked[w]) { edgeTo[w] = v; dfs(g, w); } } }
/// <summary> /// run DFS in digraph G from vertex v and compute preorder/postorder /// </summary> /// <param name="g"></param> /// <param name="v"></param> private void dfs(Digraph g, int v) { if (marked[v]) { return; } marked[v] = true; pre[v] = preCounter++; preorder.Enqueue(v); foreach (int w in g.Adj(v)) { if (!marked[v]) { dfs(g, w); } } postorder.Enqueue(v); post[v] = postCounter++; }