Fix global variable name in topological_sort.

This commit is contained in:
Filip Hlásek
2020-08-04 00:00:52 -07:00
parent 1f9da87c12
commit 5dbf857fb4

View File

@@ -2,44 +2,44 @@
#include <iostream> #include <iostream>
#include <vector> #include <vector>
int n, m; // For number of Vertices (V) and number of edges (E) int number_of_vertices, number_of_edges; // For number of Vertices (V) and number of edges (E)
std::vector<std::vector<int>> G; std::vector<std::vector<int>> graph;
std::vector<bool> visited; std::vector<bool> visited;
std::vector<int> ans; std::vector<int> topological_order;
void dfs(int v) { void dfs(int v) {
visited[v] = true; visited[v] = true;
for (int u : G[v]) { for (int u : graph[v]) {
if (!visited[u]) { if (!visited[u]) {
dfs(u); dfs(u);
} }
} }
ans.push_back(v); topological_order.push_back(v);
} }
void topological_sort() { void topological_sort() {
visited.assign(n, false); visited.assign(number_of_vertices, false);
ans.clear(); topological_order.clear();
for (int i = 0; i < n; ++i) { for (int i = 0; i < number_of_vertices; ++i) {
if (!visited[i]) { if (!visited[i]) {
dfs(i); dfs(i);
} }
} }
reverse(ans.begin(), ans.end()); reverse(topological_order.begin(), topological_order.end());
} }
int main() { int main() {
std::cout << "Enter the number of vertices and the number of directed edges\n"; std::cout << "Enter the number of vertices and the number of directed edges\n";
std::cin >> n >> m; std::cin >> number_of_vertices >> number_of_edges;
int x = 0, y = 0; int x = 0, y = 0;
G.resize(n, std::vector<int>()); graph.resize(number_of_vertices, std::vector<int>());
for (int i = 0; i < n; ++i) { for (int i = 0; i < number_of_edges; ++i) {
std::cin >> x >> y; std::cin >> x >> y;
x--, y--; // to convert 1-indexed to 0-indexed x--, y--; // to convert 1-indexed to 0-indexed
G[x].push_back(y); graph[x].push_back(y);
} }
topological_sort(); topological_sort();
std::cout << "Topological Order : \n"; std::cout << "Topological Order : \n";
for (int v : ans) { for (int v : topological_order) {
std::cout << v + 1 std::cout << v + 1
<< ' '; // converting zero based indexing back to one based. << ' '; // converting zero based indexing back to one based.
} }