-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
49 lines (45 loc) · 788 Bytes
/
BFS.cpp
File metadata and controls
49 lines (45 loc) · 788 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
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int INF= INT_MAX;
queue<int> Q;
int V;
int E;
int d[100];
vector<int>adj[100];
int main()
{
cin>>V>>E;
for(int i=0;i<E;i++)
{
int u,v;
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=0;i<V;i++)
d[i]=INF;
int s=0;
d[0]=0;
Q.push(s);
while(!Q.empty())
{
int j=Q.front();
Q.pop();
cout<<j<<" ";
int n=adj[j].size();
for(int i=0;i<n;i++)
{
int h=adj[j][i];
if(d[h]==INF)
{
d[h]=d[j]+1;
Q.push(h);
}
}
}
cout<<endl;
for(int i=0;i<V;i++)
cout<<d[i]<<" ";
}