vector<Component> FindZeroIndegreeComponents(const DirectedGraph &graph) { vector<Component> components = FindWeaklyConnectedComponents(graph); vector<bool> top_component_flags(components.size(), true); vector<int> vertices_components(graph.size()); for (int component_number = 0; component_number < components.size(); ++component_number) { for (int vertex : components[component_number]) { vertices_components[vertex] = component_number; } } for (int vertex = 0; vertex < graph.size(); ++vertex) { for (int adj_vertex : graph.GetAdjacentVertices(vertex)) { if (vertices_components[vertex] != vertices_components[adj_vertex]) { top_component_flags[vertices_components[adj_vertex]] = false; } } } vector<Component> top_components; for (int component_number = 0; component_number < components.size(); ++component_number) { if (top_component_flags[component_number]) { top_components.push_back(components[component_number]); } } return top_components; }
DirectedGraph Transpose(const DirectedGraph &graph) { DirectedGraph tr_graph = DirectedGraph(graph.size()); for (int vertex = 0; vertex < graph.size(); ++vertex) { for (int adj_vertex : graph.GetAdjacentVertices(vertex)) { tr_graph.AddEdge(Edge(adj_vertex, vertex)); } } return tr_graph; }
void DepthFirstSearch(const DirectedGraph &graph, vector<int> &order, vector<bool> &visited, int vertex) { visited[vertex] = true; for (int outgoing_vertex : graph.GetAdjacentVertices(vertex)) { if (!visited[outgoing_vertex]) { DepthFirstSearch(graph, order, visited, outgoing_vertex); } } order.push_back(vertex); }