🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Breadth-First Search (BFS) — Level Order on Graphs — Complete Beginner Guide

Data Structures FoundationsBreadth-First Search (BFS) — Level Order on Graphs🟢 Free Lesson

Breadth-First Search (BFS) — Level Order on Graphs — Complete Beginner Guide

Learning Objectives

  • Implement BFS with a queue
  • Track visited vertices to avoid loops
  • Measure distance in levels or hops
  • Find shortest paths in unweighted graphs
  • Analyze BFS time and space complexity

What Is BFS?

Breadth-first search explores a graph outward in waves. It visits the start vertex, then all neighbors, then their neighbors, and so on. The result is level order traversal on a graph.

A queue keeps the frontier in first-in first-out order so shallow nodes finish before deep nodes.

python
from collections import deque


def bfs(graph, start):
    visited = set([start])
    order = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)
    return order


graph = {
    "A": ["B", "C"],
    "B": ["A", "D", "E"],
    "C": ["A", "F"],
    "D": ["B"],
    "E": ["B", "F"],
    "F": ["C", "E"],
}

print(bfs(graph, "A"))
# A, then B and C, then D E F

Why a Queue?

The queue holds vertices waiting to expand. Newly discovered neighbors go to the rear. That guarantees vertices closer to the start leave earlier than deeper vertices.

StructureRole in BFS
QueueFrontier waiting for expansion
Visited setStops cycles and repeats
Distance mapStores level of each vertex
Parent mapRebuilds shortest path later

Shortest Path in Unweighted Graphs

With unit edge costs, BFS distance equals the fewest edges. Record the distance when first discovered.

python
from collections import deque


def bfs_distances(graph, start):
    dist = {start: 0}
    parent = {start: None}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for neighbor in graph[node]:
            if neighbor not in dist:
                dist[neighbor] = dist[node] + 1
                parent[neighbor] = node
                queue.append(neighbor)
    return dist, parent


def path_to(parent, target):
    out = []
    current = target
    while current is not None:
        out.append(current)
        current = parent[current]
    out.reverse()
    return out


dist, parent = bfs_distances(graph, "A")
print(dist["F"])
print(path_to(parent, "F"))

Level-by-Level Loop Variant

Sometimes you need levels as separate groups. Track the queue size at each layer.

python
from collections import deque


def levels(graph, start):
    visited = set([start])
    queue = deque([start])
    result = []
    while queue:
        level_size = len(queue)
        current_level = []
        for _ in range(level_size):
            node = queue.popleft()
            current_level.append(node)
            for neighbor in graph[node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)
        result.append(current_level)
    return result


print(levels(graph, "A"))

Complexity

MetricCostReason
Time adjacency listO(V plus E)Visit vertices and edges once
Time adjacency matrixO(V squared)Scan full rows
SpaceO(V)Visited, queue, maps
Queue peakUp to O(V)Wide level

V is the number of vertices and E is the number of edges.

When to Use BFS

  • Shortest path in unweighted graphs
  • Level order printing of a graph
  • Finding neighbors within k steps
  • Bipartite checking by two-coloring
  • Web crawlers exploring by depth layer
  • Solving mazes with fewest moves

BFS does not explore deeply early, so it is memory hungry on wide graphs. Depth-first search trades that for deeper dives.

BFS Dry Runs

Dry run BFS on a small graph before coding. Start at A with distance zero. Enqueue A. Dequeue A and discover B and C at distance one. Dequeue B and discover D and E at distance two. Dequeue C and discover F at distance two. Remaining nodes exit in that shallow order.

Write the queue contents after every step. If a node is marked visited only after dequeue, duplicates slip into the queue. Mark on discovery to avoid that classic bug.

StepQueue After StepDistances Known
startAA0
pop AB CA0 B1 C1
pop BC D Eplus D2 E2
pop CD E Fplus F2

Then vary the graph: add a back edge to create a cycle and confirm visited handling stops the loop. Add weights and remember BFS no longer finds the cheapest path. That boundary keeps your tool choice honest.

BFS Implementation Pitfalls

Four pitfalls account for most beginner BFS bugs.

First, mark visited when you enqueue, not when you dequeue. Otherwise the same node enters the queue from two parents and you duplicate work. Second, remember that unweighted BFS assumes every edge costs the same. Introduce a weight and you need Dijkstra instead.

Third, on directed graphs follow only outgoing edges. Reversing direction silently searches the wrong network. Fourth, for grid BFS encode coordinates carefully so neighbors do not walk off the board or revisit cells already claimed.

python
def neighbors4(r, c, rows, cols):
    for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nr, nc = r + dr, c + dc
        if 0 <= nr < rows and 0 <= nc < cols:
            yield nr, nc


print(list(neighbors4(0, 0, 3, 3)))

Drill one grid problem and one plain graph problem. Together they cover the majority of BFS interview shapes.

Key Takeaways

💡

  • BFS explores in waves using a first-in first-out queue
  • Visited tracking prevents cycles and repeated work
  • BFS gives shortest hop count on unweighted graphs
  • Time is O(V plus E) with adjacency lists
  • Use BFS for level order, fewest steps, and neighbor searches

Practice Questions

  1. Run BFS from A on a line graph A-B-C-D and list visit order with distances.
  2. Why must BFS mark vertices visited when they are enqueued rather than when dequeued?
  3. Modify the code to stop early once a target vertex distance is found.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement