Graph Traversal — BFS, DFS & Dijkstra's

H446 · 2.3 Algorithms · A-Level Computer Science

Component 02

BFS vs DFS — Overview

Breadth-First Search (BFS)

Explores all nodes at current depth before going deeper. Uses a queue.

• Process: visit node, enqueue unvisited neighbours, dequeue next

• Complexity: O(V+E)

• Finds shortest path in unweighted graphs

• Uses: web crawling, social network connections, peer-to-peer networks

Depth-First Search (DFS)

Goes as deep as possible before backtracking. Uses a stack (or recursion).

• Process: visit node, push unvisited neighbours, pop next

• Complexity: O(V+E)

• Does NOT guarantee shortest path

• Uses: maze solving, cycle detection, topological sort

Dijkstra's Algorithm

Finds shortest paths from source to all nodes in a weighted graph. Greedy approach.

• Uses a priority queue (min-heap)

• Complexity: O((V+E) log V)

• Cannot handle negative edge weights

• Uses: GPS navigation, network routing (OSPF)

Pseudocode

BFS

BFS(graph, start):
  visited = {}
  queue = [start]
  visited.add(start)
  WHILE queue not empty:
    node = queue.dequeue()
    process(node)
    FOR each neighbour of node:
      IF neighbour not in visited:
        visited.add(neighbour)
        queue.enqueue(neighbour)

DFS (iterative)

DFS(graph, start):
  visited = {}
  stack = [start]
  WHILE stack not empty:
    node = stack.pop()
    IF node not in visited:
      visited.add(node)
      process(node)
      FOR each neighbour of node:
        IF neighbour not in visited:
          stack.push(neighbour)

Dijkstra's — Worked Example

Graph: A–B:4, A–C:2, B–C:1, B–D:5, C–D:8, C–E:10, D–F:2, E–F:3. Find shortest path A→F.

StepVisitABCDEF
Init0
1A (0)42
2C (2)31012
3B (3)812
4D (8)1210
5F (10)1210 ✓

Shortest path A→F = 10

Route: A → C (2) → B (3) → D (8) → F (10)

BFS / DFS Visualiser

Unweighted graph. Click a start node, choose algorithm, then Step through.

Queue: [ ]

Visited order: