private void Dfs(DiGraph g, int v) { _marked[v] = true; _onStack[v] = true; foreach (var w in g.Adj(v)) { if (this.HasCycle()) { return; } else if (!_marked[w]) { Dfs(g, w); } else if (_onStack[w]) { _cycle = new Stack <int>(); for (int i = v; i == w; i = _edgeTo[i]) { _cycle.Push(i); } _cycle.Push(w); _cycle.Push(v); } _onStack[w] = false; } }
public TopologicalSort(DiGraph g) { DirectedCycle Dc = new DirectedCycle(g); if (!Dc.HasCycle()) { DepthFirstOrder dfo = new DepthFirstOrder(g); _order = dfo.ReversePostOrder; } }
//internal recursive processing method private void dfs(DiGraph G, int v) { _marked[v] = true; foreach (var w in G.Adj(v)) { if (!_marked[w]) { dfs(G, w); } } }
public DirectedDFS(DiGraph G, IEnumerable <int> sources) { _marked = new bool[G.V]; foreach (var s in sources) { if (!_marked[s]) { dfs(G, s); } } }
public DirectedCycle(DiGraph g) { _marked = new bool[g.V]; _edgeTo = new int[g.V]; _onStack = new Boolean[g.V]; for (int i = 0; i < g.V; i++) { if (!_marked[i]) { Dfs(g, i); } } }
//creates and returns a new Digraph in reverse, listing all V's pointing TO the indexed v(preceding v's) public DiGraph Reverse() { DiGraph R = new DiGraph(_v); for (int i = 0; i < _v; i++) { foreach (var w in _adj[i]) { R.AddEdge(w, i); R._e++; } } return(R); }
private void Dfs(DiGraph g, int v) { PreOrder.Enqueue(v); _marked[v] = true; foreach (var w in g.Adj(v)) { if (!_marked[w]) { Dfs(g, w); } } PostOrder.Enqueue(v); ReversePostOrder.Push(v); }
public DepthFirstOrder(DiGraph g) { _marked = new bool[g.V]; _preOrder = new Queue <int>(); _postOrder = new Queue <int>(); _reversePostOrder = new Stack <int>(); for (int v = 0; v < g.V; v++) { if (!_marked[v]) { Dfs(g, v); } } }
//inits the DS and calls the main processing method to start public DirectedDFS(DiGraph G, int s) { _marked = new bool[G.V]; dfs(G, s); }