forked from as-square/GRAPH-THEORY
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
52 lines (44 loc) · 940 Bytes
/
bfs.cpp
File metadata and controls
52 lines (44 loc) · 940 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
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
bool vis[N]={0};
vector<int> g[N];
int dis[N]={0};
int main() {
int n,m;
cout<<"Enter the value of n: ";
cin>>n;
cout<<"Enter the value of m: ";
cin>>m;
for (int i = 1; i <=m; i++)
{
int a,b;
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
queue<int> q;
q.push(1);
while (!q.empty())
{
int node = q.front();
vis[node]=1;
q.pop();
for(auto var :g[node])
{
if(!vis[var]){
dis[var]=dis[node]+1;
vis[var]=1;
q.push(var);
}
}
}
for(int i=1;i<=n;i++){
cout<<vis[i]<<"\n";
}
for (int i = 1; i <=n; i++)
{
cout<<i<<"--->"<<dis[i]<<"\n";
}
return 0;
}