Repository navigation
Expand file tree
/
Copy pathbfs.cpp
More file actions
73 lines (61 loc) · 1.3 KB
/
Copy pathbfs.cpp
File metadata and controls
73 lines (61 loc) · 1.3 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
/*
BFS algorithm on graphs using adjacency lists
complexity: O(n+m) where n is the number of vertices and m is the number of edges
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(int start, vector<vector<int> > &graph, vector<bool> &vis, vector<int> &lev, vector<int> &parent)
{
vis[start]=true;
lev[start]=0;
queue<int> q;
q.push(start);
while(!q.empty())
{
int u = q.front();
q.pop();
for(auto v: graph[u])
{
if(!vis[v])
{
vis[v]=true;
lev[v]=lev[u]+1;
parent[v]=u;
q.push(v);
}
}
}
}
int main()
{
int n,m;
cin>>n>>m;
vector<vector<int> > graph(n);
vector<bool> vis(n);
vector<int> lev(n), parent(n,-1);
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
u--;
v--;
graph[u].push_back(v);
graph[v].push_back(u);
}
parent[0]=0;
bfs(0,graph,vis,lev,parent); //start bfs from 0
for(int i=0;i<n;i++)
{
if(vis[i])
{
cout<<i+1<<" has been visited and its parent is "<<parent[i]+1<<"\n";
}
else
{
cout<<i+1<<" has not been visited\n";
}
}
return 0;
}