// BFS from multiple sources 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.GetAdj(v)) { if (!marked[w]) { edgeTo[w] = v; distTo[w] = distTo[v] + 1; marked[w] = true; q.Enqueue(w); } } } }
// check that algorithm computes either the topological order or finds a directed cycle private void Dfs(Digraph G, int v) // v is start vertex here { onStack[v] = true; marked[v] = true; foreach (int w in G.GetAdj(v)) { // short circuit if directed cycle found if (cycle != null) { return; } // found new vertex, so recur 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); Debug.Assert(Check()); } } onStack[v] = false; }
// --- dfs and pathes private void Dfs(Digraph G, int v) { marked[v] = true; foreach (int w in G.GetAdj(v)) { if (!marked[w]) { edgeTo[w] = v; Dfs(G, w); } } }
// DFS on graph G private void Dfs(Digraph G, int v) { marked[v] = true; id[v] = count; foreach (int w in G.GetAdj(v)) { if (!marked[w]) { Dfs(G, w); } } }
// --- Depth first search private void Dfs(Digraph G, int s) { Count++; marked[s] = true; foreach (int w in G.GetAdj(s)) { if (!marked[w]) { Dfs(G, w); } } }
private void Dfs(Digraph G, int v) { marked[v] = true; Pre.Enqueue(v); foreach (int w in G.GetAdj(v)) { if (!marked[w]) { Dfs(G, w); } } Post.Enqueue(v); ReversePost.Push(v); }