-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.cpp
45 lines (43 loc) · 1.11 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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void bfs(const vector<vector<int>>& graph, int startNode) {
vector<bool> visited(graph.size(), false);
queue<int> q;
visited[startNode] = true;
q.push(startNode);
cout << "BFS Traversal: ";
while (!q.empty()) {
int current = q.front();
q.pop();
cout << current << " ";
for (int neighbor : graph[current]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << endl;
}
int main() {
int nodes, edges;
cout << "Enter the number of nodes: ";
cin >> nodes;
cout << "Enter the number of edges: ";
cin >> edges;
vector<vector<int>> graph(nodes);
cout << "Enter the edges (node1 node2):" << endl;
for (int i = 0; i < edges; ++i) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
int startNode;
cout << "Enter the starting node for BFS: ";
cin >> startNode;
bfs(graph, startNode);
return 0;
}