-
Notifications
You must be signed in to change notification settings - Fork 2
/
1.bfs.cpp
60 lines (53 loc) · 1.01 KB
/
1.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
#include<bits/stdc++.h>
using namespace std;
int visited[1000];
int cost[1000];
vector <int> adj[1000];
void bfs(int s, int n)
{
for (int i = 0; i < n; i++)
{
visited[i] = 0;
}
queue <int> Q;
Q.push(s);
visited[s] = 1;
cost[s] = 0;
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i = 0; i < adj[u].size(); i++ )
{
int v = adj[u][i];
if(visited[v] == 0)
{
visited[v] = 1;
Q.push(v);
cost[v] = cost[u] + 1;
}
}
}
}
int main()
{
int n, e;
cout << "Enter nodes and edges" << endl;
cin >> n >> e;
for (int i = 1; i <= e; i++)
{
int x, y;
cin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x);
}
cout << "source node\n";
int s;
cin >> s;
bfs(s, n);
int nn;
cout << "Enter the measured node number\n";
cin >> nn;
cout << cost[nn];
return 0;
}