-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
66 lines (52 loc) · 1012 Bytes
/
BFS.cpp
File metadata and controls
66 lines (52 loc) · 1012 Bytes
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
/*
code by harsha_76
*/
#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V;
list<int>* adj;
public:
Graph(int v)
: V{v}, adj {new list<int>[v]}
{ }
void addEdge(int u, int v);
void bfs(int v);
};
void Graph::addEdge(int u, int v)
{
adj[u].push_back(v);
}
void Graph::bfs(int v)
{
vector<bool> visited(V, false);
std::queue<int> q;
visited[v]=true;
q.push(v);
while(!q.empty())
{
int s= q.front();
cout<<s<<' ';
q.pop();
for(auto it = adj[s].begin();it!=adj[s].end();it++)
{
if(!visited[*it])
{
visited[*it]=true;
q.push(*it);
}
}
}
cout<<'\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
Graph g(7);
g.addEdge(0, 1); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(0, 4); g.addEdge(4, 5); g.addEdge(5, 6);
g.bfs(0);
return 0;
}