Skip to content

12.3 Write a breadth-first search

You write a search of your own that works off a queue, level by level - breadth-first, or following only the nodes you choose.

You want a search that goes outward from a start node: first every node one edge away, then every node two edges away, and so on. The nodes at the same distance from the start node form a level. Often only some nodes should be followed further, or the search should stop at a certain level. You need this for:

  • the methods at each call depth from main;
  • the people a message reaches in each round of forwarding;
  • the nodes within a certain distance of a node.

The example graph calls models the calls between the ten methods of a small program. It has an edge from each method to each method it calls. The array names holds the names of the methods. Which methods lie at which call depth from main - one call away, two calls away, and so on? The call depth of a method is its level in a breadth-first search from main. The picture after frames the methods by level:

The calls between the methods
The levels from main
0: main1: parseArgs2: run3: load4: save5: show6: parse7: format8: read9: write
0: main1: parseArgs2: run3: load4: save5: show6: parse7: format8: read9: writelevel 3level 2level 1level 0
Input
  • Start node
Output
  • Level
class ByDepth extends FrontierTraverser {
final List<List<String>> levels = new ArrayList<>();
List<String> current = new ArrayList<>();
ByDepth(Graph calls) {
super(calls);
}
@Override
protected void visitNode(int method) {
current.add(names[method]);
enqueueChildren(method); // the out-nodes form the next level
}
@Override
protected void leaveLevel(int level) {
levels.add(current); // after the last node of each level
current = new ArrayList<>();
}
}
var byDepth = new ByDepth(calls);
byDepth.run(main);
// byDepth.levels: [[main], [parseArgs, run], [load, save, show],
// [parse, read, format, write]]
Full example
struct ByDepth<'a> {
names: &'a [&'static str],
levels: Vec<Vec<&'static str>>,
current: Vec<&'static str>,
}
impl FrontierHooks for ByDepth<'_> {
fn visit_node(&mut self, method: u32, control: &mut FrontierControl<'_>) {
self.current.push(self.names[method as usize]);
control.enqueue_children(method); // the out-nodes form the next level
}
fn leave_level(&mut self, _level: u32, _control: &mut FrontierControl<'_>) {
let level = std::mem::take(&mut self.current);
self.levels.push(level); // after the last node of each level
}
}
let mut by_depth = ByDepth {
names,
levels: Vec::new(),
current: Vec::new(),
};
FrontierTraverser::new(&calls).run_from(main, &mut by_depth);
// by_depth.levels: [["main"], ["parseArgs", "run"], ["load", "save", "show"],
// ["parse", "read", "format", "write"]]
Full example
class ByDepth extends FrontierTraverser {
readonly levels: string[][] = [];
current: string[] = [];
protected visitNode(method: number): void {
this.current.push(names[method]);
this.enqueueChildren(method); // the out-nodes form the next level
}
protected override leaveLevel(level: number): void {
this.levels.push(this.current); // after the last node of each level
this.current = [];
}
}
const byDepth = new ByDepth(calls);
byDepth.run(main);
// byDepth.levels: [[main], [parseArgs, run], [load, save, show],
// [parse, read, format, write]]
Full example
private sealed class ByDepth(Graph calls, string[] names) : FrontierTraverser(calls)
{
private List<string> _current = [];
public List<List<string>> Levels { get; } = [];
protected override void VisitNode(int method)
{
_current.Add(names[method]);
EnqueueChildren(method); // the out-nodes form the next level
}
protected override void LeaveLevel(int level)
{
Levels.Add(_current); // after the last node of each level
_current = [];
}
}
private static List<List<string>> MethodsByDepth(
Graph calls, string[] names, int main)
{
var byDepth = new ByDepth(calls, names);
byDepth.Run(main);
// byDepth.Levels: [[main], [parseArgs, run], [load, save, show],
// [parse, read, format, write]]
return byDepth.Levels;
}
Full example

levelslevelslevelsLevels holds a list of methods per level, as in the picture after: main at level 0; parseArgs and run at level 1; load, save and show at level 2; the four methods they call at level 3. Within a level, the methods come in the order in which they entered the queue.