I am searching for a non-recursive depth first search algorithm on graphs
in Pascal (Delphi).
I need DFS for computing strongly or bi-connected components of large graphs.
Currently I am using a recursive variant of the algorithm: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
The problem is that for such algorithm I must define a large amount of memory
to be used for a stack and that makes later problems in Windows 7,
where Open and Save Dialogs do not work because of several threads generated….
So again: I do not see how to rewrite the Tarjan DFS algorithm
to work without recursion. Do you have any suggestion –
or point to a non recursice algorithm for depth first search on graphs?
Thanks.
The algorithm as described on Wikipedia looks to reasonably easily be made non-recursive with an explicit stack. Starting out with that (included here for reference, in case Wikipedia changes):
Step 1: Remove loops containing recursion, adding labels and gotos. This is necessary to make loop variables explicit, savable and restorable (needed during recursion-simulation with stacks). A label needs to be added after
tarjan()‘s return, as we’ll jump to it in a moment.Step 2: Introduce a stack which contains all the relevant state for storing our position and computation in the loop at any point where we may be returning from recursion, or starting out at the top of the loop.
The stack:
stateis an enumeration (TopState,ReturnedState) encoding the location in the procedure. Here’s the procedure rewritten to use this stack and state rather than recursion:Step 3: Finally, we need to make sure the entry conditions are correct, for the top-level code which calls tarjan. That can easily be done by an initial push:
It could also be done by a jump, jumping immediately to
top. The code can be further cleaned up, perhaps converted to use a while or repeat loop to eliminate some of the gotos, etc., but the above should be at least functionally equivalent, eliminating the explicit recursion.