-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.txt
60 lines (56 loc) · 1.23 KB
/
BFS.txt
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
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int>adjlist[100];
vector<int>t;
int node1,node2,n,d,e,visited[100]={0},par[100]={0},level[100]={0},edge,s,v;
cout<<"Enter the node:";
cin>>n;
cout<<"Enter the edge:";
cin>>edge;
for(int i=0;i<edge;i++)
{
cin>>node1>>node2;
adjlist[node1].push_back(node2);
adjlist[node2].push_back(node1);
}
for(int i=1;i<=n;i++)
{
cout<<i<<":";
for(int j=0;j<adjlist[i].size();j++)
{
cout<<adjlist[i][j]<<" ";
}
}
cout<<"Enter source:";
cin>>d;
cout<<endl;
cout<<"Enter destination:";
cin>>s;
queue<int>q;
visited[d]=1;
q.push(d);
while(!q.empty())
{
e=q.front();
t.push_back(e);
q.pop();
for(int i=0;i<adjlist[e].size();i++)
{
v=adjlist[e][i];
if(visited[v]==0)
{
visited[v]=1;
q.push(v);
level[v]=level[e]+1;
}
}
}
cout<<level[s]<<endl;
for(int i=0;i<t.size();i++)
{
cout<<t[i]<<" ";
}
}
//my name is arik