Bird
Raised Fist0
DSA Cprogramming~10 mins

BFS Breadth First Search on Graph in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - BFS Breadth First Search on Graph
Start at source node
↓
Mark node visited
↓
Add node to queue
↓
While queue not empty
↓
Dequeue node
↓
Visit all unvisited neighbors
↓
Mark neighbors visited and enqueue
↓
Repeat loop
BFS starts at a node, visits neighbors level by level using a queue, marking nodes visited to avoid repeats.
Execution Sample
DSA C
graph = {
  'A': ['B', 'D'],
  'B': ['A', 'C'],
  'C': ['B', 'F'],
  'D': ['A', 'E'],
  'E': ['D', 'F'],
  'F': ['C', 'E']
}

def bfs(start):
    visited = set()
    queue = []
    visited.add(start)
    queue.append(start)

    while queue:
        node = queue.pop(0)
        print(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

bfs('A')
Perform BFS starting from node 'A' on the given graph.
Execution Table
StepOperationCurrent NodeQueue StateVisited SetVisual State
1Start BFSA[A]{A}A (visited)
2Dequeue nodeA[]{A}A (visited)
3Visit neighbors B, DA[B, D]{A, B, D}A (visited) -> B (visited), D (visited)
4Dequeue nodeB[D]{A, B, D}A -> B, D
5Visit neighbors C (A already visited)B[D, C]{A, B, C, D}A -> B -> C, D
6Dequeue nodeD[C]{A, B, C, D}A -> B -> C, D
7Visit neighbors E (A visited)D[C, E]{A, B, C, D, E}A -> B -> C, D -> E
8Dequeue nodeC[E]{A, B, C, D, E}A -> B -> C, D -> E
9Visit neighbors F (B visited)C[E, F]{A, B, C, D, E, F}A -> B -> C -> F, D -> E
10Dequeue nodeE[F]{A, B, C, D, E, F}A -> B -> C -> F, D -> E
11Visit neighbors (D, F visited)E[F]{A, B, C, D, E, F}A -> B -> C -> F, D -> E
12Dequeue nodeF[]{A, B, C, D, E, F}A -> B -> C -> F, D -> E
13Visit neighbors (C, E visited)F[]{A, B, C, D, E, F}A -> B -> C -> F, D -> E
14Queue empty-[]{A, B, C, D, E, F}Traversal complete
💡 Queue is empty, all reachable nodes visited
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7After 8After 9After 10After 11Final
Queue[][A][][B, D][D][D, C][C][C, E][E][E, F][F][F][]
Visited Set{}{A}{A}{A, B, D}{A, B, D}{A, B, C, D}{A, B, C, D}{A, B, C, D, E}{A, B, C, D, E}{A, B, C, D, E, F}{A, B, C, D, E, F}{A, B, C, D, E, F}{A, B, C, D, E, F}
Current Node-AABBDDCCEEF-
Key Moments - 3 Insights
Why do we mark nodes as visited before adding them to the queue?
Marking nodes visited before enqueueing (see step 3 and 5) prevents adding the same node multiple times, avoiding repeated visits and infinite loops.
Why does BFS use a queue instead of a stack?
BFS uses a queue (FIFO) to explore nodes level by level, ensuring neighbors are visited in order of distance from the start, unlike a stack which would explore depth first.
What happens when the queue becomes empty?
When the queue is empty (step 14), it means all reachable nodes have been visited and the BFS traversal is complete.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the queue state after visiting neighbors of node 'B'?
A[D, C]
B[C]
C[B, D]
D[]
💡 Hint
Check step 5 in the execution_table for queue state after visiting neighbors of B.
At which step does the BFS visit node 'E' for the first time?
AStep 9
BStep 7
CStep 5
DStep 3
💡 Hint
Look at the 'Operation' and 'Current Node' columns in execution_table to find when E is added.
If node 'F' was not connected to any node, how would the visited set change?
A{A, B, C, D, E, F}
B{A, B, D, E, F}
C{A, B, C, D, E}
D{A, B, C, D}
💡 Hint
Refer to variable_tracker for visited set and consider connectivity impact on BFS.
Concept Snapshot
BFS (Breadth First Search) explores graph nodes level by level.
Uses a queue to track nodes to visit next.
Marks nodes visited before enqueueing to avoid repeats.
Stops when queue is empty (all reachable nodes visited).
Good for shortest path in unweighted graphs.
Full Transcript
Breadth First Search (BFS) starts at a chosen node and explores all its neighbors before moving to the next level neighbors. It uses a queue to keep track of nodes to visit next. Each node is marked visited before adding to the queue to prevent revisiting. The process continues until the queue is empty, meaning all reachable nodes have been visited. This traversal visits nodes in order of their distance from the start node, making BFS useful for shortest path problems in unweighted graphs.

Practice

(1/5)
1. What does BFS (Breadth First Search) primarily use to keep track of nodes to visit next in a graph?
easy
A. A queue to explore nodes level by level
B. A stack to explore nodes deeply first
C. A hash map to store visited nodes only
D. A priority queue to explore nodes by weight

Solution

  1. Step 1: Understand BFS traversal method

    BFS explores nodes in layers, visiting all neighbors before going deeper.
  2. Step 2: Identify the data structure used

    To achieve level-by-level traversal, BFS uses a queue to store nodes to visit next.
  3. Final Answer:

    A queue to explore nodes level by level -> Option A
  4. Quick Check:

    BFS uses queue = A [OK]
Hint: BFS uses a queue, DFS uses a stack [OK]
Common Mistakes:
  • Confusing BFS with DFS and choosing stack
  • Thinking BFS uses priority queue for weights
  • Ignoring the need for a data structure to track nodes
2. Which of the following is the correct way to enqueue a node `v` in a BFS implementation using C?
easy
A. queue.push(v);
B. queue.insert(v);
C. queue.add(v);
D. enqueue(queue, v);

Solution

  1. Step 1: Recognize C queue operation syntax

    In C, queues are usually implemented with functions like enqueue(queue, value).
  2. Step 2: Identify correct enqueue function call

    queue.push and queue.add are not standard C; enqueue(queue, v) is typical.
  3. Final Answer:

    enqueue(queue, v); -> Option D
  4. Quick Check:

    Use enqueue(queue, v) in C [OK]
Hint: C uses enqueue(queue, value) for queues [OK]
Common Mistakes:
  • Using push or add which are not C queue functions
  • Confusing queue insertion with array insertion
  • Using incorrect method names from other languages
3. Consider the following graph represented as adjacency list:
0: 1, 2
1: 0, 3
2: 0, 3
3: 1, 2
If BFS starts from node 0, what is the order of nodes visited?
medium
A. [0, 2, 1, 3]
B. [0, 1, 2, 3]
C. [0, 3, 1, 2]
D. [0, 1, 3, 2]

Solution

  1. Step 1: Start BFS from node 0

    Visit 0, enqueue neighbors 1 and 2.
  2. Step 2: Visit nodes in queue order

    Dequeue 1, enqueue its unvisited neighbor 3; then dequeue 2, neighbor 3 already visited.
  3. Step 3: Visit remaining node 3

    Dequeue 3, no new neighbors.
  4. Final Answer:

    [0, 1, 2, 3] -> Option B
  5. Quick Check:

    BFS order = [0, 1, 2, 3] [OK]
Hint: BFS visits neighbors in queue order [OK]
Common Mistakes:
  • Visiting nodes in DFS order instead
  • Mixing neighbor order causing wrong sequence
  • Not marking visited nodes causing repeats
4. The following BFS code snippet has a bug. What is the error?
void bfs(int start, int n, int adj[][n]) {
  int visited[n];
  for(int i=0; i<n; i++) visited[i] = 0;
  int queue[n], front=0, rear=0;
  queue[rear++] = start;
  visited[start] = 1;
  while(front < rear) {
    int u = queue[front++];
    printf("%d ", u);
    for(int v=0; v<n; v++) {
      if(adj[u][v] == 1 && visited[v] == 0) {
        queue[rear++] = v;
        // Missing visited mark here
      }
    }
  }
}
medium
A. Visited array is not initialized
B. Queue overflow not checked
C. Visited mark missing inside neighbor loop
D. Start node not enqueued

Solution

  1. Step 1: Check visited array initialization

    Visited array is initialized to 0 for all nodes, so no issue here.
  2. Step 2: Inspect neighbor loop for visited marking

    Inside the neighbor loop, nodes are enqueued but visited[v] is not set to 1, causing repeated visits.
  3. Step 3: Confirm other options

    Queue overflow is not handled but not the main bug; start node is enqueued correctly.
  4. Final Answer:

    Visited mark missing inside neighbor loop -> Option C
  5. Quick Check:

    Mark visited when enqueueing neighbors [OK]
Hint: Always mark visited when enqueueing nodes [OK]
Common Mistakes:
  • Forgetting to mark visited inside neighbor loop
  • Assuming initialization fixes all visited issues
  • Ignoring queue overflow but it's not main bug
5. Given a graph with nodes 0 to 4 and edges: 0-1, 0-2, 1-3, 2-3, 3-4. Using BFS starting at node 0, which node is visited at the 3rd step (0-based index)?
hard
A. 2
B. 3
C. 1
D. 4

Solution

  1. Step 1: List BFS order from node 0

    Start at 0, enqueue neighbors 1 and 2. Visit order so far: [0]
  2. Step 2: Visit nodes in queue order

    Visit 1 (step 1), enqueue neighbor 3; visit 2 (step 2), neighbor 3 already enqueued.
  3. Step 3: Visit node 2 (step 3)

    Next node dequeued is 2, which is the 3rd step (0-based index).
  4. Final Answer:

    2 -> Option A
  5. Quick Check:

    BFS step 3 node = 2 [OK]
Hint: Track BFS queue order stepwise [OK]
Common Mistakes:
  • Counting steps starting at 1 instead of 0
  • Visiting neighbors out of enqueue order
  • Forgetting node 3 is enqueued twice but visited once
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard