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.
Problem
Section titled “Problem”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.
Example
Section titled “Example”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:
- Start node
- Level
Solution
Section titled “Solution”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]]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"]]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]]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;}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.
Good to know
Section titled “Good to know”- Visited once. A node counts as visited when it enters the queue. So it is visited at most
once, at the level where the search first meets it.
formatis called bysaveand byshow, and it appears once.FrontierTraverser.isVisitedFrontierControl::is_visitedFrontierTraverser.isVisitedFrontierTraverser.IsVisitedtells whether a node is visited. - Not only breadth-first.
FrontierTraverser.enqueueFrontierControl::enqueueFrontierTraverser.enqueueFrontierTraverser.Enqueueputs a single node into the queue. So the hook chooses which nodes enter it, and they need not be out-nodes. They are visited in the order in which they entered, after the rest of the current level.FrontierTraverser.currentLevelFrontierControl::current_levelFrontierTraverser.currentLevelFrontierTraverser.CurrentLeveltells the level of the node being visited, so you can stop at a certain level.FrontierTraverser.stopFrontierControl::stopFrontierTraverser.stopFrontierTraverser.Stopends the run. - Where to start.
FrontierTraverser.run(int)FrontierTraverser::run_fromFrontierTraverser.run(startNode: number)FrontierTraverser.Run(int)starts at one node.FrontierTraverser.run(IntList)FrontierTraverser::run_from_nodesFrontierTraverser.run(startNodes: IntList)FrontierTraverser.Run(ReadOnlySpan<int>)starts at several nodes, which together form level 0.FrontierTraverser.run()FrontierTraverser::runFrontierTraverser.run()FrontierTraverser.Run()starts at every node not visited yet. The visited nodes add up over the runs of one traverser. - Distances and paths come ready-made. See Find a shortest path between two nodes.
API used
Section titled “API used”FrontierTraverser.visitNode(int)FrontierHooks::visit_nodeFrontierTraverser.visitNodeFrontierTraverser.VisitNodeFrontierTraverser.enqueueChildren(int)FrontierControl::enqueue_childrenFrontierTraverser.enqueueChildrenFrontierTraverser.EnqueueChildrenFrontierTraverser.leaveLevel(int)FrontierHooks::leave_levelFrontierTraverser.leaveLevelFrontierTraverser.LeaveLevelFrontierTraverser.enqueue(int)FrontierControl::enqueueFrontierTraverser.enqueueFrontierTraverser.EnqueueFrontierTraverser.currentLevel()FrontierControl::current_levelFrontierTraverser.currentLevelFrontierTraverser.CurrentLevelFrontierTraverser.isVisited(int)FrontierControl::is_visitedFrontierTraverser.isVisitedFrontierTraverser.IsVisitedFrontierTraverser.stop()FrontierControl::stopFrontierTraverser.stopFrontierTraverser.StopFrontierTraverser.run(int)FrontierTraverser::run_fromFrontierTraverser.run(startNode: number)FrontierTraverser.Run(int)FrontierTraverser.run(IntList)FrontierTraverser::run_from_nodesFrontierTraverser.run(startNodes: IntList)FrontierTraverser.Run(ReadOnlySpan<int>)FrontierTraverser.run()FrontierTraverser::runFrontierTraverser.run()FrontierTraverser.Run()