-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtopological_sorting_dfs.cpp
More file actions
68 lines (56 loc) · 1.5 KB
/
Copy pathtopological_sorting_dfs.cpp
File metadata and controls
68 lines (56 loc) · 1.5 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
66
67
68
// Topological sorting of graph nodes using dfs
// Algorithm taken from Cormen
#include<iostream>
#include<vector>
#include<list>
#define MAX 50
using namespace std ;
vector <int> adj[MAX] ;
list <int> linkedList ;
bool visited[MAX] ;
/*Initialize the boolean values to the visited part ..Since no nodes got traversed till now */
void initialize(int nodes)
{
for (int i = 1 ; i<=nodes ;i++){
visited[i] = false ;
}
linkedList.clear() ;
}
//to perform depth first search
void dfs(int current)
{
cout << current << "\t";
visited[current] = true ;
for(int i = 0 ; i< adj[current].size() ; i++){
if (visited[adj[current][i]] == false){
dfs(adj[current][i]) ;
}
}
linkedList.push_front(current);
}
int main ()
{
int nodes , edges , x , y , i ;
cout << "Enter the total nodes in the graph\t" ;
cin >> nodes ;
cout << "Enter the total edges of the graph\t" ;
cin >> edges ;
cout << "Enter the edges pairs of the graph (eg : a b , for a->b)\n" ;
for (i = 0 ; i <edges ; i++){
cin >> x >> y ;
adj[x].push_back(y);
}
initialize(nodes) ;
cout << "The dfs traversal sequence is given as\n" ;
for (i = 1 ; i<=nodes ; i++){
if(visited[i] == false){
dfs(i);
}
}
cout << "\nThe topological sorted sequence is: " ;
list<int>::iterator it ;
for (it = linkedList.begin() ; it != linkedList.end() ; ++it){
cout << *it << " " ;
}
return 0 ;
}