-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS.cpp
More file actions
62 lines (49 loc) · 1.27 KB
/
Copy pathBFS.cpp
File metadata and controls
62 lines (49 loc) · 1.27 KB
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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void BFS(int start, vector<int> adj[], int vertices)
{
vector<bool> visited(vertices, false);
queue<int> q;
visited[start] = true;
q.push(start);
cout << "BFS Traversal starting from vertex " << start + 1 << ": ";
while (!q.empty())
{
int node = q.front();
q.pop();
cout << node + 1 << " ";
for (int neighbor : adj[node])
{
if (!visited[neighbor])
{
visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << "\n";
}
int main()
{
int vertices, edges;
cout << "Enter the number of vertices: ";
cin >> vertices;
cout << "Enter the number of edges: ";
cin >> edges;
vector<int> adj[100];
cout << "Enter the edges (u v) where 1 <= u,v <= " << vertices << ":\n";
for (int i = 0; i < edges; i++)
{
int u, v;
cin >> u >> v;
adj[u - 1].push_back(v - 1);
adj[v - 1].push_back(u - 1);
}
int startVertex;
cout << "Enter the starting vertex for BFS: ";
cin >> startVertex;
BFS(startVertex - 1, adj, vertices);
return 0;
}