private void DfsRec(Digraph digraph, int v) { //preOrder.Enqueue(v); visited[v] = true; foreach (int w in digraph.Adjacent(v)) // 6 1 5 { if (!visited[w]) { DfsRec(digraph, w); } } //postOrder.Enqueue(v); reversePostOrder.Push(v); }
public DepthFirstOrder(Digraph digraph) { //preOrder = new Queue<int>(); //postOrder = new Queue<int>(); reversePostOrder = new Stack <int>(); visited = new bool[digraph.NodeCount]; inStack = new bool[digraph.NodeCount]; for (int v = 0; v < digraph.NodeCount; v++) { if (!visited[v]) { Dfs(digraph, v); } } }
private void Dfs(Digraph digraph, int source) { Stack <int> stack = new Stack <int>(); stack.Push(source); visited[source] = true; while (stack.Count != 0) { int v = stack.Pop(); foreach (var w in digraph.Adjacent(v)) { if (!visited[w]) { visited[w] = true; stack.Push(w); } } } }
public DirectCycles(Digraph digraph) { int nodeCount = digraph.NodeCount; visited = new bool[nodeCount]; cycledPaths = new Dictionary <int, int[]>(); edgeTo = new int[nodeCount]; onStack = new bool[nodeCount]; for (int inx = 0; inx < nodeCount; inx++) { edgeTo[inx] = -1; } for (int s = 0; s < nodeCount; s++) { if (!visited[s]) { Dfs(digraph, s); } } }
private void Dfs(Digraph digraph, int s) { bool[] onPath = new bool[digraph.NodeCount]; Stack <int> stack = new Stack <int>(); stack.Push(s); visited[s] = true; onPath[s] = true; while (stack.Count != 0) { int v = stack.Pop(); //onPath[v] = false; Console.WriteLine(v); foreach (int w in digraph.Adjacent(v)) { if (!visited[w]) { edgeTo[w] = v; onPath[w] = true; visited[w] = true; stack.Push(w); } else if (onPath[w]) // already went through { Stack <int> tmp = new Stack <int>(); for (int x = v; x != w && x != -1; x = edgeTo[x]) { tmp.Push(x); } tmp.Push(w); tmp.Push(v); cycledPaths[cycledPaths.Count] = tmp.ToArray(); } } } }
private bool Dfs(Digraph digraph, int s) { Stack <int> stack = new Stack <int>(); stack.Push(s); while (stack.Count > 0) { int node = stack.Peek(); visited[node] = true; inStack[node] = true; IList <int> adjs = digraph.Adjacent(node); int aInx = 0; while (aInx < adjs.Count && visited[adjs[aInx]]) { if (inStack[adjs[aInx]]) { return(false); } aInx += 1; } if (aInx == adjs.Count) { inStack[node] = false; reversePostOrder.Push(stack.Pop()); } else { stack.Push(adjs[aInx]); } } return(true); }
public DirectedDFS(Digraph digraph, int source) { visited = new bool[digraph.NodeCount]; Dfs(digraph, source); }