Repository navigation
Expand file tree
/
Copy pathday24.cpp
More file actions
86 lines (74 loc) · 1.71 KB
/
Copy pathday24.cpp
File metadata and controls
86 lines (74 loc) · 1.71 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
//graphs in c++
#include <iostream>
#include <map>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <string>
using namespace std;
class Graph{
public:
map<string, vector<string>> adjacency_list;
void add_edge(string node1, string node2){
adjacency_list[node1].push_back(node2);
adjacency_list[node2].push_back(node1); //undirected
}
void display(){
for (auto& pair : adjacency_list){
cout<<pair.first<<" -> ";
for (string neighbour : pair.second){
cout<< neighbour << " ";
}
cout<< endl;
}
}
void bfs(string start){
set < string > visited;
queue < string > q;
q.push(start);
visited.insert(start);
while (!q.empty()) {
string node = q.front();
q.pop();
cout<< node << " ";
for (string neighbour : adjacency_list[node]) {
if (visited.find(neighbour)==visited.end()){
visited.insert(neighbour);
q.push(neighbour);
}
}
}
cout<< endl;
}
void dfs(string start) {
set <string> visited;
stack <string> s;
s.push(start);
while (!s.empty()) {
string node= s.top();
s.pop();
if (visited.find(node)== visited.end()){
visited.insert(node);
cout<<node <<" ";
for (string neighbour : adjacency_list[node]) {
if (visited.find(neighbour)== visited.end()){
s.push(neighbour);
}
}
}
}
cout<< endl;
}
};
int main(){
Graph g;
g.add_edge("A","B");
g.add_edge("A","C");
g.add_edge("B","D");
g.add_edge("C","D");
g.dfs("A");
g.display();
g.bfs("A");
return 0;
}