Kamal
Kamal

Reputation: 3178

Depth first search recursion algorithm

I am looking at the DFS pseudocode here

dfs(node start) {
 stack s;
 s.push(start);
 while (s.empty() == false) {
  top = s.top();
  s.pop();
  mark top as visited;

  check for termination condition

  add all of top's unvisited neighbors to the stack.
  mark top as not visited;
 }
}

dfs(node current) {
 mark current as visited;
 visit all of current's unvisited neighbors by calling dfs(neighbor)
 mark current as not visited;
}

Why is the author marking a vertex as not visited after visiting all its neighbours? Is that a required step here. Since we are just searching for a vertex, should it not work with out marking the vertex as not visited?

Another link here does not in fact mark the vertex as not visited after setting it as visited.

Upvotes: 1

Views: 4086

Answers (1)

Jon
Jon

Reputation: 437904

The vertex should be marked as not visited when you are looking for paths to a vertex instead of the vertex itself.

Imagine you don't mark vertexes as not visited after traversing, and that some search traverses a part of the graph and does find a path to the vertex in question. At some point the search runs out of edges to explore and retraces its steps to some earlier point, continuing from there.

If there is another path to the vertex being searched for that passes through a vertex that is also on the first path found, the algorithm would not find the second path because it would consider the common vertex as already visited.

On the other hand, if you are looking for just one path (or for just the presence of a vertex, i.e. no paths at all) then you can skip marking nodes as not visited "on your way out".

Upvotes: 4

Related Questions