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