Class DfsTraverser
- Namespace
- Graphity
- Assembly
- Graphity.Core.dll
The base class of a depth-first search of your own over a Graph. A subclass overrides
the hooks EnterNode(int) and LeaveNode(int), and a Run method starts the
search.
public abstract class DfsTraverser
- Inheritance
-
DfsTraverser
- Inherited Members
Examples
Here, calls are the calls between the methods of a program, and the postorder puts each
method after the methods it calls, except along calls that close a cycle:
private sealed class CalleesFirst(Graph calls) : DfsTraverser(calls)
{
public List<int> Order { get; } = [];
protected override bool EnterNode(int method) => true;
protected override void LeaveNode(int method) => Order.Add(method);
}
private static List<int> RunCalleesFirst(Graph calls, int main)
{
var calleesFirst = new CalleesFirst(calls);
calleesFirst.Run(main);
// calleesFirst.Order: [1, 6, 8, 3, 7, 9, 4, 5, 2, 0] - parseArgs, parse, read,
// load, format, write, save, show, run and main
return calleesFirst.Order;
}
Remarks
The search visits each node it reaches once. It calls EnterNode(int) when it reaches a node (preorder) and LeaveNode(int) when it has searched from all out-nodes of the node (postorder). It takes the out-nodes of each node in ascending order, so the hooks come in the order of a textbook recursive depth-first search. The search itself runs without recursion and keeps its stack on the heap, so a deep graph does not overflow the call stack.
Between its two hooks, a node is on the current path. The current path leads from the node where the search started to the node being searched. The hooks may call IsVisited(int) and IsOnStack(int), end the search at a node by returning false from EnterNode(int), and end the whole run with Stop().
Run() searches from every node in ascending order, Run(int) from one node and Run(ReadOnlySpan<int>) from several, such as the root nodes that RootNodes(BiAdjacentGraph) returns. The visited nodes add up over the runs of an instance: a node is visited at most once in the lifetime of the instance, and a later run skips it. A hook must not start another run of the same instance, which throws InvalidOperationException. If a run ends with an exception from a hook or from the search, the state of the instance is undefined: nodes of the interrupted path may still count as on the path, for example. A new instance is needed for further runs.
DfsEdgeTraverser also calls a hook for every edge, which suits searches that look at edges to nodes already visited. This class calls no such hook, which makes it the faster choice where node hooks suffice. FrontierTraverser searches breadth-first. Common searches are ready-made, such as TopOrder, EdgeTypes, BackEdges and FindCycle(Graph).
Instances are mutable and not safe to share between threads.
Memory: 2 bits per node for the visited state, and up to 8 x NodeCount bytes for the stack, which grows with the deepest path searched.
Constructors
DfsTraverser(Graph)
Creates a traverser for graph, with no node visited.
protected DfsTraverser(Graph graph)
Parameters
graphGraphThe graph to search.
Remarks
Time: O(NodeCount).
Properties
Graph
Gets the graph that this traverser searches.
protected Graph Graph { get; }
Property Value
Methods
EnterNode(int)
Called when the search reaches node, before its out-nodes: the preorder hook.
protected abstract bool EnterNode(int node)
Parameters
nodeintNode ID in
0..NodeCount-1.
Returns
Remarks
The search calls it once per node: for a start node, or for an unvisited out-node of the node it
is searching. From this call on, node counts as visited and is on the current
path. Returning true lets the search go on with the out-nodes of
node. Returning false skips them, and
LeaveNode(int) follows right away; out-nodes skipped this way stay unvisited unless the
search reaches them from another node.
IsOnStack(int)
Returns whether node is on the stack of the search, that is, on the current
path.
protected bool IsOnStack(int node)
Parameters
nodeintNode ID in
0..NodeCount-1.
Returns
Remarks
The current path leads from the node where the search started to the node being searched. A node is on the path from its EnterNode(int) until its LeaveNode(int). An edge from the node being searched to a node on the path closes a cycle. Outside a run, no node is on the path.
Time: O(1).
Exceptions
- ArgumentOutOfRangeException
nodeis out of range.
IsVisited(int)
Returns whether the search has reached node, in this run or in an earlier one.
protected bool IsVisited(int node)
Parameters
nodeintNode ID in
0..NodeCount-1.
Returns
- bool
true if EnterNode(int) has been called for
node.
Remarks
Time: O(1).
Exceptions
- ArgumentOutOfRangeException
nodeis out of range.
LeaveNode(int)
Called when the search leaves node, after it has searched from all its
out-nodes: the postorder hook. Does nothing unless overridden.
protected virtual void LeaveNode(int node)
Parameters
nodeintNode ID in
0..NodeCount-1.
Remarks
The search calls it once for every node it has visited, right after EnterNode(int) if
that returned false. From this call on, node is no longer on
the current path. After Stop(), it is not called for the nodes still on the path.
Run()
Searches from every node not visited yet, in ascending order, until every node is visited.
public void Run()
Remarks
A node that no earlier search has reached when its turn comes starts a search of its own.
Time: O(NodeCount + EdgeCount), plus the hooks.
Exceptions
- ArgumentException
A depth-first path is longer than 2^30 - 29 nodes.
- InvalidOperationException
Called from a hook, during a run of this instance.
Run(int)
Searches from startNode, visiting the nodes it reaches that are not visited
yet.
public void Run(int startNode)
Parameters
startNodeintNode ID in
0..NodeCount-1.
Remarks
If startNode is visited already, nothing happens.
Time: O(reachable nodes + reachable edges), plus the hooks.
Exceptions
- ArgumentOutOfRangeException
startNodeis out of range.- ArgumentException
A depth-first path is longer than 2^30 - 29 nodes.
- InvalidOperationException
Called from a hook, during a run of this instance.
Run(ReadOnlySpan<int>)
Searches from each of startNodes in list order, skipping those visited already.
public void Run(ReadOnlySpan<int> startNodes)
Parameters
startNodesReadOnlySpan<int>Node IDs, each in
0..NodeCount-1; not to be changed until the call returns.
Remarks
The list is checked before the first hook, so a start node out of range leaves the traverser unchanged. Stop() ends the whole call, not only the search from one start node.
Time: O(startNodes.Length + reachable nodes + reachable edges), plus the hooks.
Exceptions
- ArgumentOutOfRangeException
A start node is out of range.
- ArgumentException
A depth-first path is longer than 2^30 - 29 nodes.
- InvalidOperationException
Called from a hook, during a run of this instance.
Stop()
Stops the run in progress: the run returns as soon as the hook that calls this method returns, without calling another hook.
protected void Stop()
Remarks
LeaveNode(int) is not called for the nodes on the current path, but they count as visited and as no longer on the path. A later run skips every node visited so far; it does not go on where the stopped run ended. Called outside a run, this method has no effect. To cancel a run from another thread, let a hook check a flag of your own and call this method.
Time: O(1).