Recipe 003: Breadth-First Search (BFS)
Breadth-First Search is another fundamental algorithm in graph theory, it’s a must-know algorithm!
For this algorithm we need a queue.
#include <iostream>
#include <vector>
#include <queue>
#include <cstdlib>
using namespace std;
// Maximum number of nodes.
const int N = 10;
void bfs(vector<int> graph[], int root) {
bool> visited(N, false);
vector<int> Q;
queue<int> L; // To mark levels.
queue<
Q.push(root);0); // The root is at level 0.
L.push(true;
visited[root] = int prev = 0;
while (!Q.empty()) {
int u = Q.front();
int l = L.front();
Q.pop();
L.pop();
// Each level in it's own line.
if (prev != l) {
cout << endl;
}
prev = l;" ";
cout << u <<
for (int v : graph[u]) {
if (!visited[v]) {
true;
visited[v] =
Q.push(v);1); // Childs of u are part of the next level.
L.push(l +
}
}
}
}
int main(int argc, char **argv) {
int> graph[N];
vector<int n, m;
cin >> n >> m;for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
// Start Breadth-First Search at node 0
0);
bfs(graph, return EXIT_SUCCESS;
}
Example input:
5 4
0 1
0 2
2 4 2 3
Example output:
0
1 2 4 3
And that’s it. Remember, Breadth-First Search must be part of your toolbox!