Breadth-first Search
Loading editor...
#include <bits/stdc++.h>
using namespace std;
vector<int> bfs(const vector<vector<int>> &adjacency, int start) {
int n = static_cast<int>(adjacency.size()); // Number of vertices (assumes vertices are 0‑based)
vector<bool> visited(n, false); // Tracks whether a vertex has been discovered
queue<int> q; // FIFO container for the frontier
// Initialise the search
visited[start] = true;
q.push(start);
while (!q.empty()) {
int u = q.front(); q.pop(); // Dequeue the next vertex
// Explore all neighbours of u
for (int v : adjacency[u]) {
if (!visited[v]) { // If neighbour not seen before
visited[v] = true; // Mark as discovered
q.push(v); // Enqueue for later processing
}
}
}
}
Number of nodes.
Edges between nodes, one per line.