in DS recategorized by
2,682 views
3 votes
3 votes
Could someone please explain  Depth first Search using Stack? I have found different algorithms for handling the  visited flag and the way the nodes are pushed. I am having problems in solving these types of questions

- Find the nodes or number of nodes that are pushed onto stack more than once?

Could someone please help with a small example?
in DS recategorized by
by
2.7k views

1 Answer

4 votes
4 votes

Page 1

page 2

page 3

page 4

by

2 Comments

@pC thanks a lot for your answer and efforts. I have few doubts regrading the way you are implementing the Algorithm -

1. You are marking the node as visited and then pushing it onto the stack.

2. You are checking if the nodes is unvisited and only then are you pushing onto the stack by marking it as visited.

Your algorithm will ensure that there will never be any node that is pushed onto the stack more than once isnt it?

Kindly have a look at this algorithm from stackoverflow where all the adjacent nodes are pushed onto the stack and marked as visited during the pop operation. In the below algorithm every node will be pushed at least twice. Because even the parent who discovered a node will be added..

DFS(source):
  s <- new stack
  visited <- {} // empty set
  s.push(source)
  while (s is not empty):
    current <- s.pop()
    if (current is in visited):
        continue
    visited.add(current)
    // do something with current
    for each node v such that (current,v) is an edge:
        s.push(v)
0
0

Yes :) If you are looking for the implimentation code of the algorithm I have mentined do see this : https://www.tutorialspoint.com/data_structures_algorithms/depth_first_traversal.htm

0
0

Related questions