-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.cpp
62 lines (54 loc) · 1.19 KB
/
bfs.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
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void BFS(vector<int> adj[], int vertex, int source)
{
queue<int> q;
vector<bool> visited(vertex);
for(int i=0; i<vertex; i++)
visited[i] = false;
visited[source] = true;
q.push(source);
while(!q.empty())
{
int u = q.front();
q.pop();
cout << u << " ";
for(int i : adj[u])
{
if(visited[i] == false)
{
visited[i] = true;
q.push(i);
}
}
}
}
//- if graph is disconnected
void BFS_dis(vector<int> adj[], int vertex)
{
bool visited[vertex]; // int count = 0
for(int i=0; i<vertex; i++)
visited[i] = false;
for(int i=0; i<vertex; i++)
if(visited[i] == false)
BFS(adj, i, visited[]);
// void BFS(vector<int> adj, int source, int visited[])
}
int main()
{
// forming graph
int vertex, edges;
cin >> vertex >> edges;
vector<int> adj[vertex];
int x, y;
for(int i=0; i<edges; i++)
{
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
BFS(adj, vertex, 0);
return 0;
}