DFS and BFS - Non-Recursive Versions
DFS and BFS - Non-Recursive Versions
DFS(G, v0 )
Input: graph G and starting vertex v0
Output: labels L(v) for each vertex v that give the order in which the search visits the
vertices. (Each vertex label is initially zero, with a zero label designating an unvisited
vertex.)
• Count ←− 1.
• L(v0 ) ←− Count
• While T 6= ∅ do
– v ←− top of stack T
– If there is a vertex w adjacent to v with L(w) = 0 then do
∗ Count ←− Count + 1
∗ L(w) ←− Count
∗ Push w onto stack T
– Else pop v from stack T
BFS(G, v0 )
Input: graph G and starting vertex v0
Output: labels L(v) for each vertex v that give the length of the shortest path from that
vertex to v0 .
• L(v0 ) ←− 0
• While T 6= ∅ do
• The basic operation will be the label check implicit in the line “If there is a vertex w
adjacent to v with L(w) = 0 then . . . ”
• There are at most n − 1 of these label checks each time through the “While . . . ” loop.
• But the “While . . . ” loop is executed at most 2n times: each time either adds a vertex
to the stack or takes on off, and each vertex is added once and taken off once.
• This makes the total number of basic steps no more than n · 2n, so the algorithm has
efficiency in O(n2 ).
• The basic operation is again a label check, this time implicit in the line “For all w
adjacent to v with L(w) = 0 do . . . ”
• There are at most n − 1 label checks each time through the “While . . . ” loop.
• But the “While . . . ” loop is executed at most n times, since each time one vertex is
removed from the queue.
• This makes the total number of basic steps no more than n2 , so the algorithm has
efficiency in O(n2 ).
Note: Can you see how the label checks would be handled differently depending on if G is
input as an adjacency matrix or as adjacency lists? Is one better than the other?