std::vector<std::vector<int>> adj;
48 Graph(
intnodes) : n(nodes), adj(nodes) {}
55 void addEdge(
intu,
intv) { adj[u].push_back(v); }
79void dfs(
intv, std::vector<int>& visited,
80 conststd::vector<std::vector<int>>&
graph, std::stack<int>& s) {
82 for(
intneighbour :
graph[v]) {
83 if(!visited[neighbour]) {
96 intn = g.getNumNodes();
97 const auto& adj = g.getAdjacencyList();
98std::vector<int> visited(n, 0);
101 for(
inti = 0; i < n; i++) {
103 dfs(i, visited, adj, s);
107std::vector<int> ans;
114 if(ans.size() < n) {
115 throwstd::invalid_argument(
"cycle detected in graph");
128std::cout <<
"Testing for graph 1\n";
138std::vector<int> expected_1 = {5, 4, 2, 3, 1, 0};
139std::cout <<
"Topological Sorting Order: ";
140 for(
inti : ans_1) {
141std::cout << i <<
" ";
144assert(ans_1 == expected_1);
145std::cout <<
"Test Passed\n\n";
148std::cout <<
"Testing for graph 2\n";
158std::vector<int> expected_2 = {0, 1, 2, 4, 3};
159std::cout <<
"Topological Sorting Order: ";
160 for(
inti : ans_2) {
161std::cout << i <<
" ";
164assert(ans_2 == expected_2);
165std::cout <<
"Test Passed\n\n";
168std::cout <<
"Testing for graph 3\n";
176}
catch(std::invalid_argument& err) {
177assert(std::string(err.what()) ==
"cycle detected in graph");
179std::cout <<
"Test Passed\n";
Class that represents a directed graph and provides methods for manipulating the graph.
void addEdge(int u, int v)
Function that adds an edge between two nodes or vertices of graph.
const std::vector< std::vector< int > > & getAdjacencyList() const
Get the adjacency list of the graph.
Graph(int nodes)
Constructor for the Graph class.
int getNumNodes() const
Get the number of nodes in the graph.
Topological Sort Algorithm.
std::vector< int > topologicalSort(const Graph &g)
Function to get the topological sort of the graph.
static void test()
Self-test implementation.
void dfs(int v, std::vector< int > &visited, const std::vector< std::vector< int > > &graph, std::stack< int > &s)
Function to perform Depth First Search on the graph.
int main()
Main function.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4