Bird
Raised Fist0
Data Structures Theoryknowledge~6 mins

BFS traversal and applications in Data Structures Theory - Full Explanation

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Imagine you want to explore a new city and visit all places closest to you first before moving further away. This approach helps you cover nearby spots quickly and systematically. Breadth-First Search (BFS) uses a similar idea to explore nodes in a graph or tree, layer by layer, starting from a chosen point.
Explanation
How BFS Works
BFS starts at a selected node and explores all its neighbors before moving to the neighbors' neighbors. It uses a queue to keep track of nodes to visit next, ensuring nodes closer to the start are visited first. This way, BFS visits nodes in increasing order of their distance from the start.
BFS explores nodes level by level, visiting all neighbors before going deeper.
Data Structures Used
BFS uses a queue to manage the order of node visits and a set or array to keep track of visited nodes. The queue ensures nodes are processed in the order they were discovered, while the visited set prevents revisiting nodes and getting stuck in loops.
A queue and a visited set keep BFS organized and prevent repeated visits.
Shortest Path in Unweighted Graphs
Because BFS explores nodes in layers, the first time it reaches a node, it has found the shortest path to that node in terms of the number of edges. This makes BFS useful for finding the shortest path in graphs where all edges have the same cost or no weight.
BFS finds the shortest path in unweighted graphs by exploring neighbors first.
Applications of BFS
BFS is used in many areas like finding the shortest path in maps, checking if a graph is connected, solving puzzles, and spreading information in networks. It helps in tasks where exploring all options at one level before moving deeper is important.
BFS is versatile and helps solve problems involving shortest paths and level-wise exploration.
Real World Analogy

Imagine you are at a party and want to greet everyone. You first say hello to all people standing closest to you, then move on to those a bit further away, and so on. This way, you meet everyone in order of how close they are to you.

How BFS Works → Greeting all people closest to you first before moving further
Data Structures Used → Remembering who you have already greeted and who to greet next
Shortest Path in Unweighted Graphs → Meeting someone by the shortest route through friends at the party
Applications of BFS → Using this greeting method to cover the whole party efficiently
Diagram
Diagram
Start
  │
  ▼
[Node A]
  │
  ├──▶ [Node B]
  │       │
  │       ├──▶ [Node D]
  │       │
  │       └──▶ [Node E]
  │
  └──▶ [Node C]
          │
          └──▶ [Node F]
This diagram shows BFS starting at Node A, visiting neighbors B and C first, then their neighbors D, E, and F next.
Key Facts
Breadth-First Search (BFS)An algorithm that explores nodes in a graph level by level starting from a chosen node.
Queue in BFSA data structure that stores nodes to visit in the order they were discovered.
Visited SetA collection used to keep track of nodes already explored to avoid repeats.
Shortest Path in Unweighted GraphThe minimum number of edges between two nodes found using BFS.
Applications of BFSIncludes shortest path finding, connectivity checking, and level-order traversal.
Code Example
Data Structures Theory
from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    order = []

    while queue:
        node = queue.popleft()
        if node not in visited:
            visited.add(node)
            order.append(node)
            queue.extend(n for n in graph[node] if n not in visited)
    return order

# Example graph as adjacency list
graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': [],
    'F': []
}

print(bfs(graph, 'A'))
OutputSuccess
Common Confusions
BFS finds shortest paths in weighted graphs.
BFS finds shortest paths in weighted graphs. BFS only finds shortest paths in unweighted graphs; for weighted graphs, algorithms like Dijkstra's are needed.
BFS uses a stack to manage nodes.
BFS uses a stack to manage nodes. BFS uses a queue, not a stack; stacks are used in Depth-First Search (DFS).
BFS can revisit nodes multiple times.
BFS can revisit nodes multiple times. BFS keeps track of visited nodes to avoid revisiting and infinite loops.
Summary
BFS explores nodes in layers, visiting all neighbors before moving deeper.
It uses a queue and a visited set to manage the order and avoid repeats.
BFS is useful for finding shortest paths in unweighted graphs and many other applications.

Practice

(1/5)
1. What is the main data structure used in BFS (Breadth-First Search) traversal of a graph?
easy
A. Queue
B. Stack
C. Priority Queue
D. Hash Map

Solution

  1. Step 1: Understand BFS traversal method

    BFS explores nodes level by level, which requires processing nodes in the order they are discovered.
  2. Step 2: Identify the suitable data structure

    A queue follows First-In-First-Out (FIFO) order, perfect for level-wise exploration in BFS.
  3. Final Answer:

    Queue -> Option A
  4. Quick Check:

    BFS uses a queue = Queue [OK]
Hint: BFS uses FIFO order, so it needs a queue [OK]
Common Mistakes:
  • Confusing BFS with DFS which uses a stack
  • Thinking BFS uses a priority queue
  • Assuming BFS uses a hash map as main structure
2. Which of the following is the correct way to mark a node as visited in BFS to avoid revisiting it?
easy
A. Add node to a stack after visiting
B. Add node to a visited set or list immediately when enqueued
C. Add node to the queue only after processing all neighbors
D. Do not mark nodes; revisit all nodes

Solution

  1. Step 1: Understand when to mark nodes visited in BFS

    Nodes should be marked visited when they are enqueued to prevent multiple enqueues of the same node.
  2. Step 2: Identify correct marking method

    Adding nodes to a visited set immediately when enqueued ensures no duplicates in the queue.
  3. Final Answer:

    Add node to a visited set or list immediately when enqueued -> Option B
  4. Quick Check:

    Mark visited on enqueue = Add node to a visited set or list immediately when enqueued [OK]
Hint: Mark nodes visited when enqueued, not after dequeued [OK]
Common Mistakes:
  • Marking nodes visited only after dequeuing
  • Using a stack instead of a visited set
  • Not marking nodes visited at all
3. Consider the following graph edges:
0 - 1, 0 - 2, 1 - 3, 2 - 3
If BFS starts at node 0, what is the order of nodes visited?
medium
A. [0, 1, 2, 3]
B. [0, 2, 1, 3]
C. [0, 3, 1, 2]
D. [1, 0, 2, 3]

Solution

  1. Step 1: Start BFS from node 0

    Enqueue 0, visited order starts with 0.
  2. Step 2: Enqueue neighbors of 0 in order

    Neighbors are 1 and 2, enqueue 1 then 2.
  3. Step 3: Dequeue 1 and enqueue its neighbor 3

    3 is neighbor of 1, enqueue 3.
  4. Step 4: Dequeue 2, neighbor 3 already visited

    No new nodes added.
  5. Step 5: Dequeue 3, no new neighbors

    Traversal ends.
  6. Final Answer:

    [0, 1, 2, 3] -> Option A
  7. Quick Check:

    BFS order = [0, 1, 2, 3] [OK]
Hint: Visit neighbors in order they appear, enqueue before dequeue [OK]
Common Mistakes:
  • Visiting neighbors in wrong order
  • Adding nodes multiple times
  • Starting BFS from wrong node
4. The following BFS code snippet has a bug. What is the error?
visited = set()
queue = [start]
visited.add(start)
while queue:
    node = queue.pop()
    for neighbor in graph[node]:
        if neighbor not in visited:
            queue.append(neighbor)
            visited.add(neighbor)
medium
A. Not marking start node as visited before loop
B. Queue should be a stack for BFS
C. Visited nodes added after enqueueing neighbors
D. Using pop() removes from the end, causing DFS behavior

Solution

  1. Step 1: Analyze queue operations

    pop() without argument removes last element, making it LIFO (stack), not FIFO (queue).
  2. Step 2: Understand BFS requires FIFO

    BFS needs to remove from front (pop(0)) to process nodes level by level.
  3. Final Answer:

    Using pop() removes from the end, causing DFS behavior -> Option D
  4. Quick Check:

    pop() without index = DFS, not BFS [OK]
Hint: Use pop(0) for queue behavior in BFS [OK]
Common Mistakes:
  • Using pop() instead of pop(0)
  • Forgetting to mark start node visited
  • Confusing stack and queue roles
5. You want to find the shortest path in an unweighted graph from node A to node B using BFS. Which of the following modifications is necessary to track the actual path?
hard
A. Run BFS twice, once from A and once from B, then combine results
B. Use a stack instead of a queue to track the path
C. Store each node's parent when enqueuing it, then backtrack from B to A
D. Mark nodes visited only after dequeuing them

Solution

  1. Step 1: Understand BFS finds shortest path length

    BFS explores nodes level by level, so the first time B is found is shortest path length.
  2. Step 2: Track path by storing parents

    When a node is enqueued, record which node led to it (its parent). After BFS, backtrack from B to A using parents.
  3. Final Answer:

    Store each node's parent when enqueuing it, then backtrack from B to A -> Option C
  4. Quick Check:

    Parent tracking + backtrack = shortest path [OK]
Hint: Save parents on enqueue, backtrack from target [OK]
Common Mistakes:
  • Using stack instead of queue for BFS
  • Marking visited too late causing duplicates
  • Running BFS twice unnecessarily