forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: linter warnings for topological_sort. (TheAlgorithms#994)
Approving for now to enable a PR that adds graph folder to the CI build system.
- Loading branch information
Showing
1 changed file
with
25 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,47 +1,48 @@ | ||
#include <algorithm> | ||
#include <iostream> | ||
#include <vector> | ||
using namespace std; | ||
|
||
int n, m; // For number of Vertices (V) and number of edges (E) | ||
vector<vector<int>> G; | ||
vector<bool> visited; | ||
vector<int> ans; | ||
int number_of_vertices, number_of_edges; // For number of Vertices (V) and number of edges (E) | ||
std::vector<std::vector<int>> graph; | ||
std::vector<bool> visited; | ||
std::vector<int> topological_order; | ||
|
||
void dfs(int v) { | ||
visited[v] = true; | ||
for (int u : G[v]) { | ||
if (!visited[u]) | ||
for (int u : graph[v]) { | ||
if (!visited[u]) { | ||
dfs(u); | ||
} | ||
} | ||
ans.push_back(v); | ||
topological_order.push_back(v); | ||
} | ||
|
||
void topological_sort() { | ||
visited.assign(n, false); | ||
ans.clear(); | ||
for (int i = 0; i < n; ++i) { | ||
if (!visited[i]) | ||
visited.assign(number_of_vertices, false); | ||
topological_order.clear(); | ||
for (int i = 0; i < number_of_vertices; ++i) { | ||
if (!visited[i]) { | ||
dfs(i); | ||
} | ||
} | ||
reverse(ans.begin(), ans.end()); | ||
reverse(topological_order.begin(), topological_order.end()); | ||
} | ||
int main() { | ||
cout << "Enter the number of vertices and the number of directed edges\n"; | ||
cin >> n >> m; | ||
int x, y; | ||
G.resize(n, vector<int>()); | ||
for (int i = 0; i < n; ++i) { | ||
cin >> x >> y; | ||
std::cout << "Enter the number of vertices and the number of directed edges\n"; | ||
std::cin >> number_of_vertices >> number_of_edges; | ||
int x = 0, y = 0; | ||
graph.resize(number_of_vertices, std::vector<int>()); | ||
for (int i = 0; i < number_of_edges; ++i) { | ||
std::cin >> x >> y; | ||
x--, y--; // to convert 1-indexed to 0-indexed | ||
G[x].push_back(y); | ||
graph[x].push_back(y); | ||
} | ||
topological_sort(); | ||
cout << "Topological Order : \n"; | ||
for (int v : ans) { | ||
cout << v + 1 | ||
std::cout << "Topological Order : \n"; | ||
for (int v : topological_order) { | ||
std::cout << v + 1 | ||
<< ' '; // converting zero based indexing back to one based. | ||
} | ||
cout << '\n'; | ||
std::cout << '\n'; | ||
return 0; | ||
} |