-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBFS.cpp
76 lines (56 loc) · 1.25 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>
using namespace std;
vector <int> G[100];
void BFS(int nodes,int source)
{
bool visited[nodes+1];
int distance[nodes+1];
for(int i=1;i<=nodes;i++)
{
visited[i]=false;
distance[i]=0;
}
visited[source]=true;
distance[source]=0;
queue<int> Q;
Q.push(source);
while(!Q.empty())
{
int a=Q.front();
Q.pop();
for(int i=0;i<G[a].size();i++)
{
int b=G[a][i];
if(!visited[b])
{
visited[b]=true;
distance[b]=distance[a]+1;
Q.push(b);
}
}
}
for(int i=1;i<=nodes;i++)
{
printf("%d to %d = %d\n",source,i, distance[i]);
}
}
int main()
{
int nodes,edges,source;
printf("Enter the number of nodes:");
scanf("%d",&nodes);
printf("Enter the number of edges:");
scanf("%d",&edges);
int a,b;
printf("Enter edges:");
for(int i=0;i<edges;i++)
{
scanf("%d%d",&a,&b);
G[a].push_back(b);
G[b].push_back(a);
}
printf("Enter source:");
scanf("%d",&source);
BFS(nodes,source);
return 0;
}