12.1 Write a depth-first search without recursion
You write a depth-first search of your own, with hooks that are called when a node is entered and when it is left.
Problem
Section titled “Problem”You want to go through a graph and compute something on the way. Many such computations can be written as a depth-first search with some code of your own. Written recursively, they overflow the call stack on deep graphs, such as a long chain of calls or a deeply nested syntax tree. You need this for:
- a value of each node computed from the values of its out-nodes, such as the sizes of subtrees or costs;
- the nodes in the order in which the search finishes them, such as each method after the methods it calls, if the calls have no cycle;
- a search that stops at the first node that matches.
Example
Section titled “Example”The example graph family models a family tree with one parent
per person, over four generations. It has an edge from each parent to each child. Ada is the
root, and her children are Ben and Cleo. How many
descendants does each person have? These are the person’s
children, grandchildren and so on, without the person. The picture after shows the counts in
brackets:
- Start node
- Person with the number of descendants
Solution
Section titled “Solution”leaveNodeleave_nodeleaveNodeLeaveNode is called after the search has finished
the subtree of a node, so the counts of its children are ready:
// graph, a field of DfsTraverser, is the graph it searches.class Descendants extends DfsTraverser { final int[] count;
Descendants(Graph family) { super(family); count = new int[family.nodeCount()]; }
@Override protected boolean enterNode(int person) { return true; // search from the children of every person }
@Override protected void leaveNode(int person) { // Called after the whole subtree of the person: the counts of the children are // complete. for (int child : graph.outNodes(person)) { count[person] += 1 + count[child]; } }}var descendants = new Descendants(family);descendants.run(ada);// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...// The hooks are a type of your own; each receives a DfsControl, whose graph() is the// graph the DfsTraverser searches.struct Descendants { count: Vec<u32>,}
impl DfsHooks for Descendants { fn enter_node(&mut self, _person: u32, _control: &mut DfsControl<'_>) -> bool { true // search from the children of every person }
fn leave_node(&mut self, person: u32, control: &mut DfsControl<'_>) { // Called after the whole subtree of the person: the counts of the children // are complete. for &child in control.graph().out_nodes(person).iter() { self.count[person as usize] += 1 + self.count[child as usize]; } }}let mut descendants = Descendants { count: vec![0; family.node_count() as usize],};DfsTraverser::new(&family).run_from(ada, &mut descendants);// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...// this.graph, a field of DfsTraverser, is the graph it searches.class Descendants extends DfsTraverser { readonly count = new Int32Array(this.graph.nodeCount);
protected enterNode(person: number): boolean { return true; // search from the children of every person }
protected override leaveNode(person: number): void { // Called after the whole subtree of the person: the counts of the children are // complete. for (const child of this.graph.outNodes(person)) { this.count[person] += 1 + this.count[child]; } }}const descendants = new Descendants(family);descendants.run(ada);// descendants.count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, ...// Graph, a property of DfsTraverser, is the graph it searches.private sealed class Descendants(Graph family) : DfsTraverser(family){ public int[] Count { get; } = new int[family.NodeCount];
protected override bool EnterNode(int person) { return true; // search from the children of every person }
protected override void LeaveNode(int person) { // Called after the whole subtree of the person: the counts of the children // are complete. foreach (int child in Graph.OutNodes(person)) { Count[person] += 1 + Count[child]; } }}
private static int[] CountDescendants(Graph family, int ada){ var descendants = new Descendants(family); descendants.Run(ada); // descendants.Count: [9, 4, 3, 2, 0, 2, 0, 0, 0, 0] - Ada has 9, Ben 4, Cleo 3, // ... return descendants.Count;}countcountcountCount holds the number of descendants of
each person: 9 for Ada, 4 for Ben, 3 for Cleo, and 0 for each person without children, as in
the picture after.
Good to know
Section titled “Good to know”- Where to start.
DfsTraverser.run(int)DfsTraverser::run_fromDfsTraverser.run(startNode: number)DfsTraverser.Run(int)starts at one node.DfsTraverser.run(IntList)DfsTraverser::run_from_nodesDfsTraverser.run(startNodes: IntList)DfsTraverser.Run(ReadOnlySpan<int>)starts at several nodes in turn.DfsTraverser.run()DfsTraverser::runDfsTraverser.run()DfsTraverser.Run()starts at every node not visited yet, in ascending order. The visited nodes add up over the runs of one traverser: a later run skips the nodes that an earlier one visited. - Pruning.
enterNodeenter_nodeenterNodeEnterNodereturns whether to search from the out-nodes of a node, andfalseskips them. In a tree, that skips the subtrees of its children. In other graphs, the search may still reach those nodes from another node. - State.
DfsTraverser.isVisitedDfsControl::is_visitedDfsTraverser.isVisitedDfsTraverser.IsVisitedtells whether the search has reached a node.DfsTraverser.isOnStackDfsControl::is_on_stackDfsTraverser.isOnStackDfsTraverser.IsOnStacktells whether the node is on the current path.DfsTraverser.stopDfsControl::stopDfsTraverser.stopDfsTraverser.Stopends the run from a hook. - The order. Out-nodes are searched in ascending order, so a graph always gives the same search.
- Ready-made. The number of descendants of a node in a tree is
PreorderAncestry.subtreeSizeOfPreorderAncestry::subtree_size_ofPreorderAncestry.subtreeSizeOfPreorderAncestry.SubtreeSizeOfminus 1. See List a node and all its descendants. You may also want an order in which each method comes after the methods it calls, and in which the methods on a common cycle come together. See Put the nodes in dependency order although the graph has cycles. A search of your own is for values that Graphity does not compute, such as a sum of your own data over each subtree. - Every edge. To see the edges as well and decide which to follow, see React to every edge of a depth-first search.
API used
Section titled “API used”DfsTraverser.enterNode(int)DfsHooks::enter_nodeDfsTraverser.enterNodeDfsTraverser.EnterNodeDfsTraverser.leaveNode(int)DfsHooks::leave_nodeDfsTraverser.leaveNodeDfsTraverser.LeaveNodeDfsTraverser.run(int)DfsTraverser::run_fromDfsTraverser.run(startNode: number)DfsTraverser.Run(int)DfsTraverser.run(IntList)DfsTraverser::run_from_nodesDfsTraverser.run(startNodes: IntList)DfsTraverser.Run(ReadOnlySpan<int>)DfsTraverser.run()DfsTraverser::runDfsTraverser.run()DfsTraverser.Run()DfsTraverser.isVisited(int)DfsControl::is_visitedDfsTraverser.isVisitedDfsTraverser.IsVisitedDfsTraverser.isOnStack(int)DfsControl::is_on_stackDfsTraverser.isOnStackDfsTraverser.IsOnStackDfsTraverser.stop()DfsControl::stopDfsTraverser.stopDfsTraverser.StopGraph.outNodes(int)Graph::out_nodesGraph.outNodesGraph.OutNodesPreorderAncestry.subtreeSizeOf(int)PreorderAncestry::subtree_size_ofPreorderAncestry.subtreeSizeOfPreorderAncestry.SubtreeSizeOf