-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.cpp
73 lines (60 loc) · 1.54 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
#include <chrono>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
class BFS {
map<int, vector<int>> graph = {
{0, {1, 2}}, {1, {0, 2}}, {2, {0, 3, 4}}, {3, {2}}, {4, {2}}};
const int start_node = 0;
public:
BFS() {
cout << "BFS execution started.\n";
this->start();
}
~BFS() { cout << "BFS execution done.\n"; }
private:
void start() {
auto start_time = chrono::high_resolution_clock::now();
// initialize the queue
queue<int> q;
// add the start node to the queue
q.push(start_node);
// visited set
set<int> visited;
// loop while q is not empty
while (!q.empty()) {
// pop the front node
int node = q.front();
q.pop();
cout << node << "\n";
// mark visited
visited.insert(node);
// go for the connected neighbours
for (auto &n : graph.at(node)) {
if (visited.count(n) == 0) {
q.push(n);
visited.insert(n);
}
}
// visited set
cout << "Visited: ";
for (auto &v : visited) {
cout << v << " ";
}
cout << "\n";
}
// Capture the end time
auto end_time = chrono::high_resolution_clock::now();
// Calculate the time difference
auto duration =
chrono::duration_cast<chrono::milliseconds>(end_time - start_time);
cout << "Execution time: " << duration.count() << " ms\n";
}
};
int main() {
BFS bfs;
return 0;
}