graph-theorytraversalgraph-traversal

Iterative graph traversal: non-BFS and non-DFS ordering


Consider this traversal algorithm in pseudocode:

Traverse(G, v):
    S is stack
    stack.push(v)
    label v as visited
    while S is not empty:
        v = S.pop()
        for all w in G.adjacentNodes(v) do:
            if w is not labeled:
                label w
                S.push(w)

This traversal algorithm differs from BFS in its use of the stack instead of queue and from DFS in the moment when it marks a visited vertex (in iterative DFS you mark it as visited when you pop it from the stack). It also provides ordering different from both these approaches.

I have the following questions:

  1. Is this traversal correct for a graph of any complexity, i.e. will it visit all vertices of the connected component in which the initial vertex v lies?
  2. When should DFS be preferred to this approach? The original DFS creates duplicates in the stack, does it have advantages?

I've looked at similar questions on this site, but they don't provide satisfactory and complete answers.


Solution

  • It's a hybrid. It "visits" from left to right the siblings (a breadth-first element) but separates the handling from the visit, as the handling is done in depth-first fashion.

    So for each node:

    To answer your question: yes, this will successfully traverse the graph and it depends on your goals when it is to be preferred. But objective reasons for preference for this algorithm could stem from a desire to get a breadth-first from right to left.

    But, if "visiting" does not do any magic besides marking a node as being visited, then you could easily use a depth-first search with descending sibling order instead, because that only differs from your algorithm by its non-separation of visit from handling.