CHAP. 8] GRAPH THEORY 175
EXAMPLE 8.4 Suppose the DFS Algorithm 8.5 in Fig. 8-31 is applied to the graph in Fig. 8-30. The vertices
will be processed in the following order:
A, D, L, K, C, J, M, B
Specifically, Fig. 8-32(a)shows the sequence of vertices being processed and the sequence of waiting lists
in STACK. (Note that after vertexAis processed, its neighbors,B,C, andDare added to STACK in the order
firstB, thenC, and finallyD; henceDis on the top of the STACK andDis the next vertex to be processed.)
Each vertex, excludingA, comes from an adjacency list and hence corresponds to an edge of the graph. These
edges form a spanning tree ofGwhich is pictured in Fig. 8-32(b). The numbers indicate the order that the edges
are added to the spanning tree, and the dashed lines indicate backtracking.
Fig. 8-32
Breadth-first Search
The general idea behind a breadth-first search beginning at a starting vertexAis as follows. First we process
the starting vertexA. Then we process all the neighbors ofA. Then we process all the neighbors of neighbors
ofA. And so on. Naturally we need to keep track of the neighbors of a vertex, and we need to guarantee that
no vertex is processed twice. This is accomplished by using a QUEUE to hold vertices that are waiting to be
processed, and by a field STATUS which tells us the current status of a vertex.
The breadth-first search (BFS) algorithm appears in Fig. 8-33, Again the algorithm will process only those
vertices which are connected to the starting vertexA, that is, the connected component includingA. Suppose one
wants to process all the vertices in the graphG. Then the algorithm must be modified so that it begins again with
another vertex (which we callB) that is still in the ready state(STATUS= 1 ). This vertexBcan be obtained by
traversing through the list of vertices.
EXAMPLE 8.5 Suppose the breadth-first search (BFS) Algorithm 8.6 in Fig. 8-33 is applied to the graph in
Fig. 8-30. The vertices will be processed in the following order:
A, B, C, D, K, L, J, M
Specifically, Fig. 8-34(a)shows the sequence of waiting lists in QUEUE and the sequence of vertices being
processed (Note that after vertexAis processed, its neighbors,B,C, andDare added to QUEUE in the order first
B, thenC, and finallyD; henceBis on the front of the QUEUE and so B is the next vertex to be processed.)Again,
each vertex, excludingA, comes from an adjacency list and hence corresponds to an edge of the graph. These
edges form a spanning tree ofGwhich is pictured in Fig. 8-34(b). Again, the numbers indicate the order that
the edges are added to the spanning tree. Observe that this spanning tree is different from the one in Fig. 8.32(b)
which came from a depth-first search.