Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 13: Graphs — Representation, BFS and DFS

A graph is a set of nodes (also called vertices) joined by edges. It is the most versatile structure in computer science: road networks are graphs, social networks are graphs, the links between web pages form a graph, and so do the states of a puzzle. Many problems that do not look like graphs at all — a maze, a family tree, a set of tasks with prerequisites — become easy once you see the graph hiding inside them.

The first decision is how to store a graph. An adjacency list — a dictionary mapping each node to its list of neighbours — is the usual choice in Python: it is compact, easy to build, and fast to iterate over a node's neighbours. An adjacency matrix — a grid where a 1 marks an edge — answers "is there an edge between A and B?" instantly, but uses O(V^2) space, which is wasteful for sparse graphs. For most contest problems, the adjacency list is the right answer.

# An undirected graph as an adjacency list.
graph = {
    "A": ["B", "C"],
    "B": ["A", "D"],
    "C": ["A", "D"],
    "D": ["B", "C", "E"],
    "E": ["D"],
}


def bfs(graph, start):
    seen = {start}
    order = []
    queue = [start]
    while queue:
        node = queue.pop(0)
        order.append(node)
        for nb in graph[node]:
            if nb not in seen:
                seen.add(nb)
                queue.append(nb)
    return order


print(bfs(graph, "A"))  # ['A', 'B', 'C', 'D', 'E']

BFS and DFS: two ways to walk a graph

There are two fundamental ways to visit every node of a graph. Breadth-first search (BFS) uses a queue: it visits all of a node's neighbours before moving deeper, so it explores in expanding layers — like ripples from a stone dropped in water. Depth-first search (DFS) uses a stack (or recursion): it follows one path as far as it goes before backtracking, like exploring a maze by always turning left. BFS finds the shortest path in an unweighted graph, because the first time it reaches a node is by the shortest route. DFS is simpler to write recursively and is the natural fit for problems like counting connected components or detecting cycles.

Both searches visit each node and each edge once, so both cost O(V + E) time, where V is the number of nodes and E the number of edges. The practical difference is the order of visiting and the data structure: a queue for BFS, a stack for DFS. One performance note: the BFS above uses queue.pop(0) on a list, which is O(n) per pop — for large graphs, use collections.deque with popleft(), which is O(1). Small details like that are what separate a correct solution from a fast one.

Going further

Graphs come in more flavours than the undirected example in this lesson. A directed graph has one-way edges — a web of links, where page A linking to page B does not mean B links to A. A weighted graph has a cost on each edge, which is the subject of Lesson 16. And a tree is a special graph: connected, with no cycles, and with exactly one path between any two nodes. Trees are common enough to deserve their own techniques, but every tree algorithm is also a graph algorithm with the cycle case removed — which is why learning graphs first makes trees easy.

The choice between an adjacency list and an adjacency matrix is a trade-off worth stating precisely. The list uses O(V + E) space and iterates a node's neighbours in time proportional to its degree; the matrix uses O(V^2) space but answers "is there an edge from A to B?" in O(1). For a sparse graph — most real graphs, where each node connects to only a few others — the list wins easily. The matrix wins when the graph is dense, or when you need to test edges constantly, as in some dynamic programming over graphs. In a contest, reach for the list unless you have a specific reason not to.

A good exercise is to run BFS and DFS on the same small graph by hand, on paper, and to write down the order each one visits the nodes. Use the graph from this lesson, or draw your own with a branch that is long and a branch that is wide. BFS will visit the wide branch first, level by level; DFS will dive down the long branch before it comes back. The two orders look completely different, and that difference is the whole reason the two searches exist: BFS is for questions about distance, DFS is for questions about structure, and choosing the wrong one is usually the first mistake in a graph problem.

Key Terms

Graph
A set of nodes joined by edges; models networks, maps, links and states.
Node (vertex)
One point in a graph, such as a city or a web page.
Edge
A connection between two nodes; may be directed (one-way) or undirected (two-way).
Adjacency list
A dictionary mapping each node to its list of neighbours; the usual way to store a graph.
Adjacency matrix
A grid marking which pairs of nodes are joined; fast edge tests but O(V²) space.
Breadth-first search (BFS)
Explores a graph layer by layer using a queue; finds shortest paths in unweighted graphs.
Depth-first search (DFS)
Explores a graph by following one path as far as possible, using a stack or recursion.
Connected component
A group of nodes joined to each other by paths, with no edges to the rest of the graph.

Discussion Questions

  1. Why does BFS find the shortest path in an unweighted graph, while DFS does not? Think about the order each one visits nodes in.
  2. When would you choose an adjacency matrix over an adjacency list? What does the matrix do better?
  3. A maze is a graph. What are its nodes and edges, and which search would you use to find the exit — and which to find the shortest route?

Practice Questions

  1. In the example graph, what order does BFS visit from A, and why is C visited before D?
  2. What is the time complexity of BFS, and what do V and E stand for?
  3. Why should a large BFS use collections.deque instead of a list as its queue?
  4. Give one problem BFS solves better than DFS, and one DFS solves better than BFS.
  5. Is the example graph directed or undirected? How can you tell?
Show answers
  1. ['A', 'B', 'C', 'D', 'E']. BFS visits all neighbours of A (B and C) before moving to the next layer, where D is found.
  2. O(V + E), where V is the number of nodes and E the number of edges. Each node is processed once and each edge is examined once.
  3. list.pop(0) is O(n); deque.popleft() is O(1). With a list, removing from the front shifts every remaining item.
  4. BFS: shortest path in an unweighted graph. DFS: counting connected components or detecting cycles. BFS's layer order gives shortest paths; DFS's deep exploration suits exhaustive structural questions.
  5. Undirected. Every edge appears in both directions: A lists B, and B lists A.
Keep reading to complete this lesson