Quiz 2

Graph Traversal — BFS and DFS

860 words
4 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Graph Traversal — BFS and DFS ## 🎯 Learning Objectives By the end of this topic, you will be able to: 1. **Implement** BFS using a queue data structure 2.

Graph Traversal — BFS and DFS

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Implement BFS using a queue data structure
  2. Implement DFS using a stack or recursion
  3. Compare BFS vs. DFS in terms of space, time, and use cases
  4. Apply BFS to find shortest path in unweighted graphs
  5. Apply DFS for cycle detection and connectivity

📋 Prerequisites


📖 Core Content

19.1 Intuition: Two Ways to Explore

Imagine exploring a museum with many rooms connected by corridors.
  • BFS is like a wave: explore all rooms closest to you first, then move outward. You'd see all rooms 1 step away, then all rooms 2 steps away, etc.
  • DFS is like exploring one corridor fully before backtracking. You go deep into one wing, then return and try the next.
💡 Why this matters: BFS finds shortest paths in unweighted graphs (like Google Maps for non-weighted roads). DFS is used for topological sorting, cycle detection, and solving mazes.

19.2 Breadth-First Search (BFS)

Algorithm:
  1. Start from source vertex ss. Mark ss as visited, enqueue it.
  2. While queue is not empty:
    • Dequeue vertex vv
    • Visit each unvisited neighbor ww of vv: mark visited, enqueue ww
  3. All vertices reachable from ss are now visited.
text
BFS(G, s):
  visited[s] = true
  queue.enqueue(s)
  while queue not empty:
    v = queue.dequeue()
    for each neighbor w of v:
      if not visited[w]:
        visited[w] = true
        queue.enqueue(w)
Time complexity: O(V+E)O(V + E) with adjacency list, O(V2)O(V^2) with adjacency matrix. Space complexity: O(V)O(V) for queue + visited array. Applications:
  • Shortest path in unweighted graphs (the first time BFS reaches a node, it's via the shortest path)
  • Web crawling
  • Social network "friend-of-friend" distance
  • Finding connected components

19.3 Depth-First Search (DFS)

Algorithm (recursive):
  1. Mark current vertex vv as visited
  2. Recursively visit each unvisited neighbor
text
DFS(G, v):
  visited[v] = true
  for each neighbor w of v:
    if not visited[w]:
      DFS(G, w)
Algorithm (iterative, using stack):
  1. Push source ss onto stack
  2. While stack not empty:
    • Pop vv
    • If vv not visited: mark visited, push all neighbors Time complexity: O(V+E)O(V + E) with adjacency list. Space complexity: O(V)O(V) for stack + visited. Applications:
  • Topological sorting
  • Cycle detection
  • Finding connected components
  • Solving puzzles/mazes
  • Detecting bipartite graphs (Diagram)

19.4 Comparison

FeatureBFSDFS
Data structureQueueStack (or recursion)
MemoryO(V)O(V) (keeps entire frontier)O(V)O(V) (keeps one path)
Shortest path✅ Yes (unweighted)❌ No
Cycle detection
Topological sort
Connected components
When to useAll paths short, close to sourceDeep exploration, need recursion

19.5 Worked Examples

Example 1: BFS on graph V={1,2,3,4}V=\{1,2,3,4\}, edges {(1,2),(1,3),(2,4),(3,4)}\{(1,2), (1,3), (2,4), (3,4)\}, start at 1.
StepQueueVisitingVisited Set
1[1]-{1}
2[2,3]1{1,2,3}
3[3,4]2{1,2,3,4}
4[4]3{1,2,3,4}
5[]4{1,2,3,4}
BFS order: 1,2,3,41, 2, 3, 4 Example 2: DFS on same graph, start at 1. DFS order (depends on neighbor order): 1,2,4,31, 2, 4, 3 or 1,3,4,21, 3, 4, 2

📐 Key Formulas — Summary Table

MetricBFSDFS
TimeO(V+E)O(V+E)O(V+E)O(V+E)
SpaceO(V)O(V) (queue)O(V)O(V) (stack)
Finds shortest path
Cycle detection

⚠️ Common Pitfalls

Pitfall 1: Confusing Queue vs. Stack

BFS uses queue (FIFO) — first discovered, first explored. DFS uses stack (LIFO) — last discovered, first explored.

Pitfall 2: Forgetting to Mark Visited Before Enqueueing

In BFS, mark visited when ENQUEUEING, not when dequeuing. Otherwise, duplicate entries cause inefficiency.

Pitfall 3: Infinite Loop in DFS Due to Cycles

Without a visited set, DFS on a graph with cycles will loop forever.

📝 Practice Questions

Q1: For graph with edges {(1,2),(1,3),(2,4),(3,4)}, what's the BFS order from 1?
1,2,3,41, 2, 3, 4
1,2,3,4\boxed{1,2,3,4} Q2: What data structure does BFS use?
Queue.
Queue\boxed{\text{Queue}} Q3: What data structure does DFS use?
Stack (or recursion).
Stack\boxed{\text{Stack}} Q4: Which algorithm finds shortest path in unweighted graphs?
BFS.
BFS\boxed{\text{BFS}} Q5: Time complexity of BFS on adjacency list?
O(V+E)O(V + E)
O(V+E)\boxed{O(V+E)} Q6: Can DFS be used for topological sorting?
Yes — DFS with a stack to record finish times.
Yes\boxed{\text{Yes}} Q7: For a complete graph KnK_n, how many vertices does BFS visit from any start?
All nn vertices.
n\boxed{n} Q8: What's the space complexity of BFS in worst case?
O(V)O(V) (if all vertices are on the frontier at once).
O(V)\boxed{O(V)}

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.