-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs_graphs.cpp
More file actions
143 lines (68 loc) · 1.58 KB
/
bfs_graphs.cpp
File metadata and controls
143 lines (68 loc) · 1.58 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include "essentials.cpp"
class Graph{
int vertices;
vector<list<int>>adjacency_list;
public:
Graph(int vertices);
void add_edge_undirected(int v, int w);
void add_edge_directed(int source, int dest);
void print_graph();
void get_listsize();
void bfs(int vertex);
};
Graph::Graph(int number){
this->vertices=number;
this->adjacency_list.resize(number);
}
void Graph::add_edge_undirected(int v, int w){
adjacency_list[v].push_back(w);
adjacency_list[w].push_back(v);
}
void Graph::add_edge_directed(int source, int dest){
adjacency_list[source].push_back(dest);
}
void Graph::print_graph(){
for(int i=0;i<this->adjacency_list.size();i++){
cout<<"vertices connected to node "<<i <<" are ";
//cout<<*i;
for(auto it:adjacency_list[i]){
cout<<it<<" ";
}
cout<<endl;
}
}
void Graph::get_listsize(){
cout<<"Number of vertices are "<<this->vertices<<endl;
cout<<this->adjacency_list.size()<<endl;
}
void Graph::bfs(int vertex)
{
queue<int>q;
q.push(vertex);
bool*visited =new bool[vertices];
visited[vertex]=true;
while(!q.empty()){
int top=q.front();
q.pop();
cout<<top<<" ";
for(list<int>:: iterator i=adjacency_list[top].begin();i!=adjacency_list[top].end();++i){
if(!visited[*i]){
q.push(*i);
visited[*i]=true;
}
}
}
}
int main(){
Graph g(5);
g.get_listsize();
g.add_edge_directed(0,2);
g.add_edge_directed(0,3);
g.add_edge_directed(1,0);
g.add_edge_directed(2,1);
g.add_edge_directed(3,4);
g.add_edge_directed(4,0);
g.print_graph();
g.bfs(2);
return 1;
}