Represent networks as vertices and edges, distinguish directed and undirected graphs, and understand adjacency, paths and graph traversal.
01
Learning objectives
Define vertices, edges, degree, path and cycle.
Distinguish directed and undirected graphs.
Represent a small graph with an adjacency list or matrix.
Explain breadth-first and depth-first traversal at a conceptual level.
02
Lesson notes
A graph consists of vertices (also called nodes) and edges that connect pairs of vertices. A graph can model a road network, friendship connections, computer networks, web links or dependencies. Unlike a tree, a general graph may contain cycles and may have multiple different paths between two vertices.
In an undirected graph an edge has no direction: if A is connected to B, the connection works both ways. In a directed graph an edge has an orientation, such as A to B but not necessarily B to A. Weighted graphs attach a value such as distance, cost or latency to each edge.
An adjacency list stores, for each vertex, the vertices directly connected to it. An adjacency matrix uses a table in which a cell records whether an edge exists (or its weight). Lists are often space-efficient for sparse graphs; matrices provide fast edge-existence checks but use space proportional to the square of the number of vertices.
Breadth-first search (BFS) explores neighbours layer by layer using a queue. Depth-first search (DFS) follows one path deeply before backtracking, using recursion or a stack. BFS finds a shortest path in an unweighted graph; DFS is useful for reachability, cycle checks and exploring structure.
03
Worked code examples
Worked example
The adjacency list represents the connections and the queue explores reachable vertices from A.
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A"],
"D": ["B"]
}
visited = set()
queue = ["A"]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
queue.extend(graph[node])
print(sorted(visited))
Output
['A', 'B', 'C', 'D']
04
Key terminology
Vertex
A node representing an entity in a graph.
Edge
A connection between two vertices.
Adjacency list
A representation storing each vertex and its neighbours.
BFS
Breadth-first search, which explores a graph layer by layer using a queue.
05
Common misconceptions
Common mistake
Every graph must be a tree.
Correct understanding
Graphs may contain cycles, multiple paths and disconnected components.
Common mistake
DFS and BFS always visit nodes in the same order.
Correct understanding
Their traversal orders differ because BFS uses a queue and DFS uses a stack or recursion.