Skip to content
ComputerCS
Start learning

Algorithms and Problem Solving · Lesson 3.6.3

Graph Algorithms: BFS and DFS

Explore networks using Breadth-First Search and Depth-First Search, and understand the queue/stack structures that drive their traversal order.

01

Learning objectives

  • Explain how BFS visits graph vertices level by level.
  • Explain how DFS follows a branch before backtracking.
  • Trace BFS using a queue and DFS using a stack or recursion.
  • Compare the uses and traversal properties of BFS and DFS.
  • Recognise the O(V + E) complexity for adjacency-list traversal.
02

Lesson notes

A graph represents vertices connected by edges. Graph algorithms help explore networks, map routes and analyse relationships. Breadth-First Search (BFS) starts from a vertex and explores all currently reachable neighbours before moving to the next layer. It uses a first-in-first-out queue to remember which vertices should be processed next.

BFS begins by marking the start vertex as visited and enqueuing it. It repeatedly dequeues a vertex, processes it, then enqueues each unvisited neighbour. A visited set prevents loops and duplicate processing when the graph contains cycles. In an unweighted graph, BFS can find a shortest path measured by the number of edges.

Depth-First Search (DFS) explores as far as possible along one branch before backtracking to explore another. It uses a stack or the program call stack through recursion. DFS is useful for reachability, connected components and exploring dependency structures. It does not generally guarantee the shortest path in an unweighted graph.

With an adjacency-list representation, BFS and DFS visit each vertex at most once and inspect each edge a bounded number of times, giving O(V + E) time, where V is the number of vertices and E is the number of edges. The actual visitation order can differ based on the order in which neighbours are stored.

03

Worked code examples

Worked example

The queue visits the neighbours of A before moving deeper. Reordering adjacency lists can change the exact order while preserving BFS layer behaviour.

from collections import deque

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

queue = deque(["A"])
visited = {"A"}
order = []
while queue:
    node = queue.popleft()
    order.append(node)
    for neighbour in graph[node]:
        if neighbour not in visited:
            visited.add(neighbour)
            queue.append(neighbour)

print("BFS order:", order)
Output
BFS order: ['A', 'B', 'C', 'D', 'E']
04

Key terminology

Vertex

A node in a graph.

Edge

A connection between two vertices.

BFS

Breadth-First Search; graph traversal that explores level by level using a queue.

DFS

Depth-First Search; graph traversal that follows a branch and backtracks using a stack or recursion.

Visited set

A record of vertices already processed or discovered.

05

Common misconceptions

Common mistake

BFS always uses a stack.

Correct understanding

BFS uses a FIFO queue; DFS uses a stack or recursion.

Common mistake

DFS always finds the shortest path.

Correct understanding

DFS explores depth-first and does not generally guarantee shortest paths in unweighted graphs.

06

Check your understanding

1. Which structure drives BFS?

2. Which structure drives iterative DFS?

3. Which search finds a shortest path in an unweighted graph?

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.