



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Figures 8.12 to 8.20 show a trace of the DFS algorithm applied to a graph. The figures show the content of the stack during the execution of the algorithm.
Figure 8.12: Trace of Depth-first-search algorithm: source vertex โsโ
Figure 8.13: Trace of DFS algorithm: vertex โaโ popped
Figure 8.14: Trace of DFS algorithm: vertex โcโ popped
Figure 8.15: Trace of DFS algorithm: vertex โfโ popped
Figure 8.18: Trace of DFS algorithm: vertex โbโ popped
Figure 8.19: Trace of DFS algorithm: vertexโdโ popped
Figure 8.20: Trace of DFS algorithm: the final DFS tree
Each execution of line 3 or line 8 in the TRAVERSE -DFS algorithm takes constant time. So the overall running time is O(V + E). Since the graph is connected, V โค E + 1, this is O(E).
If we implement the bag by using a queue , we have breadth-first search (BFS). Each execution of line 3 or line 8 still takes constant time. So overall running time is still O(E).
If the graph is represented using an adjacency matrix , the finding of all the neighbors of vertex in line 7 takes O(V) time. Thus depth-first and breadth-first take O(V 2 ) time overall.
Either DFS or BFS yields a spanning tree of the graph. The tree visits every vertex in the graph. This fact is established by the following lemma:
The DFSVISIT routine is as follows: