-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cpp
More file actions
66 lines (56 loc) · 1.24 KB
/
Graph.cpp
File metadata and controls
66 lines (56 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void dfs(int node, vector<int> visited, stack<int> st, vector<vector<int>> adj)
{
visited[node] = 1;
for (auto it : adj[node])
{
if (!visited[it])
{
dfs(it, visited, st, adj);
}
}
st.push(node);
}
void toppLogicalSort(vector<vector<int>> adj, int nodes)
{
stack<int> st;
vector<int> visited = {0};
for (int i = 0; i < nodes; i++)
{
if (!visited[i])
{
dfs(i, visited, st, adj);
}
}
vector<int> ans;
while (!st.empty())
{
ans.push_back(st.top());
cout<<st.top()<<" ";
st.pop();
}
}
int main()
{
int n, m;
cout << "Enter the number of nodes and edges: ";
cin >> n >> m;
vector<vector<int>> adj(n);
cout << "Enter the edges (u, v) (0-indexed):" << endl;
for (int i = 0; i < m; i++)
{
int u, v;
cin >> u >> v;
// validation to prevent segfault a`
if (u < 0 || u >= n || v < 0 || v >= n)
{
cerr << "Invalid edge: (" << u << ", " << v << ")" << endl;
return 1;
}
adj[u].push_back(v);
}
toppLogicalSort(adj,n);
return 0;
}