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:
- 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?
- 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.