-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs_graph.cpp
53 lines (43 loc) · 910 Bytes
/
bfs_graph.cpp
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
//bfs
//graph
#include <iostream>
#include <queue>
#include <vector>
#include <list>
using namespace std;
void addEdge(vector<list<int> >&graph,int u,int v) {
graph[u].push_back(v);
}
void bfs(vector<list<int> > graph,int start) {
vector<bool>visited;
visited.resize(graph.size(),false);
queue<int>q;
visited[start] = true;
q.push(start);
while(!q.empty()) {
int node = q.front();
q.pop();
cout<<node<<" ";
for(int x: graph[node]) {
if(!visited[x]) {
visited[x] = true;
q.push(x);
}
}
}
cout<<endl;
}
int main()
{
vector<list<int> > graph;
int V=4;
graph.resize(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 0);
addEdge(graph, 2, 3);
addEdge(graph, 3, 3);
bfs(graph,1);
return 0;
}