Worked Examples: Graphs, BFS & DFS

These examples are designed to step through the logical process of applying graph traversal concepts.

Example 1: BFS Trace
❓ Problem: Run BFS from A: A→{B,C}, B→{D}, C→{D,E}, D→{}, E→{}
💡 Solution: Queue: [A] → [B,C] → [C,D] → [D,E] → [E]. Order: A, B, C, D, E. Distances: A:0, B:1, C:1, D:2, E:2.
Example 2: DFS Timestamps
❓ Problem: Run DFS from A: A→{B,C}, B→{D}, C→{}, D→{C}. Record discovery/finish times.
💡 Solution: A: d=1, f=8. B: d=2, f=7. D: d=3, f=6. C: d=4, f=5. Note: C discovered via D, not directly from A.
Example 3: Edge Classification
❓ Problem: In the DFS above, what type is edge (D→C)?
💡 Solution: When D visits C, C is WHITE → Tree Edge. If C were GRAY → Back Edge (cycle). If BLACK → Forward/Cross Edge.
Example 4: Bipartite Check
❓ Problem: Is this graph bipartite? A-B, B-C, C-D, D-A, A-C
💡 Solution: Color A=Red, B=Blue, C=Red, D=Blue. Edge A-C: both Red → Not bipartite (odd cycle A-B-C-A).
Example 5: BFS vs DFS Complexity
❓ Problem: What is the time complexity of BFS and DFS?
💡 Solution: Both are $O(V + E)$. Each vertex visited once, each edge examined once.
Example 6: Adjacency Matrix vs List
❓ Problem: When to use adjacency matrix vs adjacency list?
💡 Solution: Matrix: $O(1)$ edge check, $O(n^2)$ space. Best for dense graphs. List: $O(V+E)$ space, $O(\deg(v))$ to iterate neighbors. Best for sparse graphs.