Breadth-first search
Breadth-first search uses a queue to visit neighbours in layers. In a network with equal-cost edges, the first visit gives the fewest edges from the start.
Simple example
Start at room 1. Room 2 is one doorway away and room 3 is two. Print the number of doors needed to reach room 3.
const std = @import("std");
fn show(value: i64) !void {
var buffer: [64]u8 = undefined;
var writer = std.fs.File.stdout().writer(&buffer);
try writer.interface.print("{d}\n", .{value});
try writer.interface.flush();
}
pub fn main() !void {
const offsets = [_]i64{0, 1, 2, 2};
const edges = [_]i64{1, 2};
var distance = [_]i64{0, -1, -1};
var queue = [_]i64{0, 0, 0};
var head: i64 = 0;
var tail: i64 = 1;
while (head < tail) {
const room: i64 = queue[@intCast(head)];
head += 1;
var i: i64 = offsets[@intCast(room)];
while (i < offsets[@intCast((room + 1))]) {
const other: i64 = edges[@intCast(i)];
if (distance[@intCast(other)] == -1) {
distance[@intCast(other)] = (distance[@intCast(room)] + 1);
queue[@intCast(tail)] = other;
tail += 1;
}
i += 1;
}
}
try show(distance[2]);
}
2
Everyday examples
Count shuttle links
A goes directly to B and C. C goes to D. What is the fewest number of links from A to D?
First visit B and C at distance one. From C, reach D at distance two.
Spread a class announcement
A tells B and C in the first round. Both know D. How many times should D join the next round?
Mark D when first queued. The second invitation sees that D is already waiting.
Find an unreachable room
A corridor connects rooms 1 and 2. Room 3 is in a separate building. What happens when you search from 1 for 3?
After visiting 2, the queue empties. Report that no path was found.
Cost and limits
Mark a vertex when it enters the queue to avoid adding it repeatedly. With neighbour lists, one search takes linear time in the visited vertices and edges.