I’m trying to traverse a graph with DFS.
But when I tried to pass visited node list as a function’s parameter, I found there is a problem.
When I reached at the node which has no connected node except its previous node, the recursive call ends and the information about visited nodes disappears so fall into infinite loop…
Is there an any way to keep an information about visited nodes except using imperative way?
Elaborating on Jeffrey’s answer, you have several different styles available. I give here only snippets that I haven’t tested, so there may be small or large mistakes.
You can use side-effects everywhere:
The “visit” applies the imperative function
actionto all nodes inthe graph.
You can store the visited node in a mutable reference, but thread
the state of the traversal as an accumulator
accinstead ofsequencing side-effects directly. This would correspond to a use of
the State monad.
You can reuse this state-passing logic to also pass the visited
node information.
Finally, you can move to a tail-recursive traversal by passing
information about which nodes should be computed next in the first
recursive call. This corresponds to a general transformation into
Continuation Passing Style, but with a domain-specific representation
of continuations (simply nodes to visit).
Jeffrey remarks that with this presentation, you can change the
traversal order from DFS to BFS by simply changing the way
to_visitis updated, adding children nodes to the end of the sequence rather
than at the beginning (which requires a queue structure to be
algorithmically efficient).