← Learning Hub
Advanced

Graphs: BFS and DFS

A graph is a set of nodes connected by edges: cities and roads, people and friendships, web pages and links. Store it as an adjacency list - each node with its neighbours.

Graphs model connections: roads between cities, friends on social media, links between pages, dependencies between tasks. Once you see a problem as a graph, standard algorithms - BFS for shortest steps, DFS for exploring, Dijkstra for cheapest paths - solve it.

Example
You can edit this code.

Breadth-first search (BFS) - shortest path in steps

Example
You can edit this code.

Depth-first search (DFS) - explore fully, e.g. count islands

Example
You can edit this code.
BFS uses a queue and finds the fewest steps. DFS uses recursion (or a stack) and is simpler for "visit everything connected". Both are O(V + E): every node and edge once. For roads with distances, use Dijkstra's algorithm with a heap.
Key points
  • Store graphs as adjacency lists (dict of lists).
  • BFS finds fewest steps; DFS explores fully.
  • Dijkstra finds cheapest paths with non-negative weights.

📝 Test yourself

1. Which search finds the path with the fewest steps?
2. Why keep a 'seen' set?
3. Fill in the name of the 'node: neighbours' way of storing a graph:
adjacency