Breadth-first search
Finds shortest distances from a source vertex in an unweighted graph. For a weighted graph with nonnegative edge weights, use Dijkstra.
Implementation
vector<int> bfs(vector<vector<int>> const& G, int source) {
vector<int> dist(G.size(), -1);
queue<int> Q;
dist[source] = 0;
Q.push(source);
while (!Q.empty()) {
int v = Q.front();
Q.pop();
for (int u : G[v]) {
if (dist[u] != -1) continue;
dist[u] = dist[v] + 1;
Q.push(u);
}
}
return dist;
}
Interface
G is an adjacency list. Each vertex u in G[v] represents an edge from v to u. For an undirected edge, include both directions.
| Operation | Description | Time |
|---|---|---|
bfs(G, source) |
Returns the distance from source to each vertex, or -1 for unreachable vertices. |
is the number of vertices and is the number of edges.