forked from csfx-py/hacktober2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalsortdfs(graph).cpp
More file actions
122 lines (118 loc) · 2.85 KB
/
Topologicalsortdfs(graph).cpp
File metadata and controls
122 lines (118 loc) · 2.85 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <bits/stdc++.h>
using namespace std;
template<typename T>
class Graph
{
public:
map<T,list<T>> h;
Graph()
{
}
void addmanycities(T x ,T y,bool bir=true)
{
h[x].push_back(y);
if(bir)
{
h[y].push_back(x);
}
}
void print()
{
for(auto key:h)
{
T k=key.first;
cout<<k<<"---> ";
for(auto tt:key.second)
{
cout<<tt<<" ";
}
cout<<endl;
}
}
void dfs_helper(T node,map<T,bool>&visited)
{
visited[node]=true;
cout<<node<<" "<<endl;
for(T neigh:h[node])
{
if(!visited[neigh])
{
dfs_helper(neigh,visited);
}
}
}
void dfs_helper2(T node,map<T,bool>&visited,list<T> &ordering)
{
visited[node]=true;
for(auto neigh:h[node])
{
if(!visited[neigh])
{
dfs_helper2(neigh,visited,ordering);
}
}
ordering.push_front(node);
}
void dfstopological()
{
map<T,bool> visited;
list<T> ordering;
for(auto i:h)
{
T node=i.first;
if(!visited[node])
{
dfs_helper2(node,visited,ordering);
}
}
for(auto i:ordering)
{
cout<<i<<"----->";
}
}
void dfs(T src)
{
map<T,bool> visited;
dfs_helper(src,visited);
cout<<endl;
int co=1;
for(auto neigh:h)
{
T city=neigh.first;
if(!visited[city])
{
dfs_helper(city,visited);
co++;
}
}
cout<<"The cities that was left are "<<co<<endl;
}
};
int main() {
Graph<string> g;
/*g.addmanycities("amritsar","jaipur");
g.addmanycities("amristar","delhi");
g.addmanycities("delhi","jaipur");
g.addmanycities("delhi","mumbai");
g.addmanycities("mumbai","jaipur");
g.addmanycities("mumbai","bhopal");
g.addmanycities("delhi","bhopal");
g.addmanycities("mumbai","banglore");
g.addmanycities("delhi","agra");
g.addmanycities("Andman","nicobar");
*/
g.addmanycities("English","Programming Logic",false);
g.addmanycities("Maths","Programming Logic",false);
g.addmanycities("Programming Logic","HTML",false);
g.addmanycities("Programming Logic","Python",false);
g.addmanycities("Programming Logic","Java",false);
g.addmanycities("Programming Logic","JS",false);
g.addmanycities("Python","Web Dev",false);
g.addmanycities("CSS","JS",false);
g.addmanycities("JS","Web Dev",false);
g.addmanycities("Java","Web Dev",false);
g.addmanycities("Python","Web Dev",false);
// g.print();
//g.dfs("amritsar");
g.dfstopological();
}