// Postorder Traversal bool dfs(int vertex, DirectedGraph graph, Stack <int> order, bool[] visited, bool[] recStack) { if (visited[vertex]) { return(true); } visited[vertex] = true; recStack[vertex] = true; var adj = graph.GetVertexAdjcency(vertex); for (int i = 0; i < adj.Count; i++) { if (!visited[adj[i]] && !dfs(adj[i], graph, order, visited, recStack)) { return(false); } else if (recStack[adj[i]]) { return(false); } } order.Push(vertex); recStack[vertex] = false; return(true); }
void FillStronglyConnectedComponent(int vertex, bool[] visited, DirectedGraph graph, StronglyConnectedComponent scc) { visited[vertex] = true; scc.Vertices.Add(vertex); foreach (var adj in graph.GetVertexAdjcency(vertex)) { if (!visited[adj]) { FillStronglyConnectedComponent(adj, visited, graph, scc); } } }
void PostOrder(int vertex, Stack <int> stack, bool[] visited, DirectedGraph graph) { visited[vertex] = true; foreach (var adj in graph.GetVertexAdjcency(vertex)) { if (!visited[adj]) { PostOrder(adj, stack, visited, graph); } } stack.Push(vertex); }
int[] GetIndegrees(DirectedGraph graph) { var indegrees = new int[graph.V]; for (int i = 0; i < graph.V; i++) { var adj = graph.GetVertexAdjcency(i); for (int j = 0; j < adj.Count; j++) { indegrees[adj[j]]++; } } return(indegrees); }
protected override void Sort(DirectedGraph graph, ICollection <int> items) { var indegrees = GetIndegrees(graph); var queue = new Queue <int>(); for (int i = 0; i < indegrees.Length; i++) { if (indegrees[i] == 0) { queue.Enqueue(i); indegrees[i] = -1; items.Add(i); } } while (queue.Count > 0) { var vertex = queue.Dequeue(); var adj = graph.GetVertexAdjcency(vertex); for (int i = 0; i < adj.Count; i++) { indegrees[adj[i]]--; if (indegrees[adj[i]] == 0) { queue.Enqueue(adj[i]); items.Add(adj[i]); } } } if (items.Count != graph.V) { items.Clear(); } }