So I recently implemented a non-recursive version of DFS. Turns out that I can mark the nodes "visited" as soon as they are pushed on the stack or when they are popped out. The problem which I was working on specifically stated to mark it "visited" when pushed on stack. Are both versions some kind of DFS. Or is it like one is DFS and the other is not. Any suggestions are welcomed.
What I think is that if I do the second way, it will mimic the recursive dfs. But why does the other one work?
A recursive dfs (please ignore this)
dfsRec(node)
{
visitedArray[node]=1;
for all neighbours of node
if they aren't visited
dfsRec(neighbour);
}
dfs(startNode)
{
visitedArray;
dfsRec(startNode);
}