0% found this document useful (0 votes)
45 views

DFS Using Stack

This document describes how depth-first search (DFS) can be implemented using a stack. It outlines the standard DFS algorithm and then presents a version of the DFS-Visit procedure that uses a stack S instead of recursion. In this iterative implementation, unvisited vertices are pushed onto the stack and popped off one by one, with their neighbors searched and also added to the stack, until the stack is empty and all reachable vertices have been visited.

Uploaded by

bayentapas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

DFS Using Stack

This document describes how depth-first search (DFS) can be implemented using a stack. It outlines the standard DFS algorithm and then presents a version of the DFS-Visit procedure that uses a stack S instead of recursion. In this iterative implementation, unvisited vertices are pushed onto the stack and popped off one by one, with their neighbors searched and also added to the stack, until the stack is empty and all reachable vertices have been visited.

Uploaded by

bayentapas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

DFS using stack

The DFS algorithm:


DFS(G)
1. % initialization

2. for each u in V do

3. color[u] ← W hite

4. p[u] ← N IL

5. end for

6. % now the main loop

7. for each u in V do

8. if color[u] = W hite do

9. DF S − V isit(G, u)

10. end if

11. end for


The procedure DFS-Visit can be implemented recursively, as in the textbook (given last lecture),
or can be implemented using stack.
A version of DFS-Visit using stack: DFS-Visit’(G, u):

1. stack S ← ∅ % initialize S to the empty stack

2. push(S, u)

3. while S is not empty do

4. x ← pop(S)

5. if color[x] = W hite do

6. time ← time + 1

7. s[x] ← time

8. color[x] ← Gray

9. push(S, x)

10. for each v in Adj[x] do

11. if color[v] = W hite do

12. p[v] ← x

1
13. push(S, v)

14. end if

15. end for

16. else if color[x] = Gray do

17. time ← time + 1

18. f [x] ← time

19. color[x] ← Black

20. end if

21. end while

You might also like