Sub topic 3
Storing and Using Graphs
Assume basic programming with lists, dictionaries, sets, queues, stacks, and simple big-O notation. An adjacency matrix stores a graph in a two-dimensional table. Row i and column j represent an edge from vertex i to vertex j.
Use None when no edge exists. For an undirected graph, store the same value in both directions. For a directed graph, store it in only one direction. A value can also represent an edge weight.
vertices = ["A", "B", "C"]
index = {name: i for i, name in enumerate(vertices)}
matrix = [[None] * len(vertices) for _ in vertices]
def add_edge(u, v, weight=1, directed=False):
matrix[index[u]][index[v]] = weight
if not directed:
matrix[index[v]][index[u]] = weight
add_edge("A", "B")
add_edge("A", "C", 4)
print(matrix)Adjacency List or Matrix
An adjacency list stores only existing neighbors. A matrix uses space for every possible pair.
| Operation | Adjacency list | Adjacency matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Test one edge | O(degree) | O(1) |
| Find all neighbors | O(degree) | O(V) |
| Best for | Sparse graphs | Dense graphs |
Choose a matrix when fast edge lookup matters or the graph is dense. Choose a list when most possible edges do not exist.
Breadth-First Search with a Matrix
Breadth-first search (BFS) visits vertices by increasing number of edges from a start vertex. With a matrix, checking each row takes O(V), so the full traversal costs O(V²).
from collections import deque
def bfs(matrix, start):
seen = {start}
order = []
queue = deque([start])
while queue:
u = queue.popleft()
order.append(u)
for v, weight in enumerate(matrix[u]):
if weight is not None and v not in seen:
seen.add(v)
queue.append(v)
return orderDijkstra’s Algorithm
Dijkstra’s algorithm finds shortest paths from one source when every weight is non-negative. With a matrix and a simple minimum search, it costs O(V²). Negative weights require another algorithm, such as Bellman–Ford.
Directed Acyclic Graphs
A directed acyclic graph (DAG) has directed edges but no directed cycle. DAGs model prerequisites, build steps, and workflows. Their dependencies can be arranged in a topological order.
Minimum Spanning Trees
A minimum spanning tree (MST) is a lowest-total-weight set of edges that connects every vertex in a connected, undirected, weighted graph without cycles. Kruskal’s and Prim’s algorithms find MSTs for network-design problems.
Exercise
When should you prefer an adjacency matrix over an adjacency list?
Show answer
Prefer it when the graph is dense or when constant-time edge lookup is important.