Lesson 37 +35 XP

Graph Traversals - Breadth-First & Depth-First Search

Graph Traversals - Breadth-First & Depth-First Search

Traversing a graph means visiting every vertex reachable from a start vertex exactly once. Unlike a tree, a graph may contain cycles and a vertex may be reachable along many paths, so a traversal must remember which vertices it has already seen - otherwise it would loop forever. The two standard methods are breadth-first search (BFS) and depth-first search (DFS).

1. Vertex States

The textbook (Lipschutz) algorithms give each vertex a STATUS:

STATUSStateMeaning
1ReadyNot yet reached
2WaitingReached and placed in the queue/stack, not yet processed
3ProcessedRemoved and processed

A vertex is added to the queue or stack only while it is ready, so no vertex is processed twice.

2. Breadth-First Search (BFS)

Idea: visit the start vertex, then all its neighbours, then all their unvisited neighbours, and so on - level by level, like ripples spreading in water. A queue (FIFO) remembers the order in which vertices were reached.

Algorithm BFS(G, S)
for each vertex V of G do
    STATUS[V] ← 1               // ready
ENQUEUE(Q, S); STATUS[S] ← 2    // waiting
while Q is not empty do
    N ← DEQUEUE(Q)
    process N; STATUS[N] ← 3    // processed
    for each neighbour M of N do
        if STATUS[M] = 1 then
            ENQUEUE(Q, M)
            STATUS[M] ← 2

3. Depth-First Search (DFS)

Idea: go as deep as possible along one path; when a vertex has no unvisited neighbour, backtrack to the previous vertex and try another branch - like exploring a maze by always taking the next unexplored corridor. A stack (or recursion, which uses the call stack) remembers where to backtrack to.

Recursive DFS

Algorithm DFS(G, V)
VISITED[V] ← TRUE
process V
for each neighbour W of V do
    if VISITED[W] = FALSE then
        DFS(G, W)               // go deeper first

Stack version (Lipschutz)

Identical to BFS but with a STACK: push the start vertex; repeatedly pop the top vertex, process it, and push all its ready neighbours (setting them to waiting).

4. Worked Example: the A-F Graph

Edges: A-B, A-C, B-C, B-D, C-D, C-E, D-E, D-F (and a self-loop at F). Neighbours are taken in alphabetical order.

DIAGRAM
        B --------- D --------- F   (self-loop at F)
      / |         / |
     A  |       /   |
      \ |     /     |
        C --------- E

Adjacency lists: A: B C | B: A C D | C: A B D E | D: B C E F | E: C D | F: D F

Trace from A (queue: front on the left; stack: top on the right):

BFS stepProcessQUEUE afterDFS stepProcessSTACK after
start-Astart-A
1AB C1AB C
2BC D2CB D E
3CD E3EB D
4DE F4DB F
5EF5FB
6F-6B-
  • BFS order: A B C D E F
  • DFS order (stack version): A C E D F B
  • DFS order (recursive): A B C D E F - from A go to B, from B to C, from C to D, from D to E; E has no new neighbour, so backtrack to D and go to F.

Different (equally correct) orders arise from different neighbour orders - in an exam, state the order you use.

BFS tree and DFS tree

The edges used to reach new vertices form a spanning tree of the (connected) graph.

DIAGRAM
   BFS tree (levels)                 Recursive DFS tree

   level 0:      A                        A
               /   \                      |
   level 1:   B     C                     B
              |     |                     |
   level 2:   D     E                     C
              |                           |
   level 3:   F                           D
                                         / \
                                        E   F

The BFS level of each vertex is its shortest distance (in edges) from A: B and C are 1 edge away, D and E 2, F 3. The DFS tree is long and thin because DFS dives deep.

5. Analysis

Each vertex is enqueued/pushed and processed once, and each adjacency list is scanned once.

RepresentationBFS / DFS timeWhy
Adjacency listO(n + e)Every vertex once + every list node once
Adjacency matrixO(n2)Scanning row of each vertex costs n

Extra space: O(n) for the visited array plus the queue or stack (or recursion depth).

6. BFS vs DFS

BasisBFSDFS
Data structureQueue (FIFO)Stack (LIFO) or recursion
Order of visitingLevel by level, nearest firstDeep along one path, then backtrack
Spanning treeShort and wideLong and thin
Shortest path (unweighted)Yes - the first time a vertex is reached is by a shortest pathNo
MemoryCan hold a whole level (wide graphs)Holds one path (deep graphs)
Typical usesShortest paths, level order, bipartite test, web crawling, nearest neighbours in networksCycle detection, topological sort, connected/strongly connected components, maze solving, backtracking
TimeO(n + e)O(n + e)

7. Applications of Traversal

Connected components

Run BFS or DFS from any unvisited vertex; every vertex it reaches is in the same component. Repeat from the next unvisited vertex.

PSEUDO
Algorithm COMPONENTS(G)
COUNT ← 0
for each vertex V do VISITED[V] ← FALSE
for each vertex V of G do
    if VISITED[V] = FALSE then
        COUNT ← COUNT + 1
        DFS(G, V)               // marks one whole component
return COUNT

The graph is connected exactly when COUNT = 1.

Cycle detection

  • Undirected graph: during DFS, reaching an already-visited vertex that is not the parent of the current vertex means a cycle.
  • Directed graph: reaching a vertex that is still on the recursion stack (a back edge) means a cycle.

Other uses

  • Path finding: is there a path from u to v? (Traverse from u and see whether v is reached.)
  • Topological sort of a DAG: output vertices in reverse order of DFS finishing times (see the Beyond Syllabus lesson on topological sorting).
  • Spanning tree of an unweighted graph: the BFS or DFS tree.
💡 Tip

Key points to remember - Mark vertices as visited - graphs can have cycles. - BFS: queue, level by level, gives shortest paths in unweighted graphs. - DFS: stack/recursion, go deep then backtrack; used for cycles, components and topological sort. - Both: O(n + e) with adjacency lists, O(n2) with a matrix. - A-F graph from A: BFS A B C D E F; stack DFS A C E D F B.

🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Write the BFS and DFS algorithms using STATUS (ready, waiting, processed). Trace both from A on the given graph. (10 Marks)
  • Write: both algorithms, the queue and stack trace table, and the resulting orders.
  • Q2. Differentiate between BFS and DFS. Give two applications of each. (5 Marks)
  • Write: the comparison table; BFS → shortest path, level order; DFS → cycle detection, topological sort.
  • Q3. How can a traversal find the connected components of a graph? (5 Marks)