COMPUTER ENGINEER

← BlogDATA STRUCTURES / ALGORITHMSPython example pack ↓

Graphs and paths · 25 / 53

Graph models and adjacency representations

Understand → trace → implement → justify

1 min reading · allow extra time for practice

A graph G=(V,E) represents entities and relations. Specify directedness, weights, parallel edges, self-loops and disconnected components. An undirected edge is typically represented twice in adjacency lists; do not confuse stored entries with E.

Matrices need V² cells, constant edge lookup and O(V) neighbour scans. Lists need O(V+E) space and degree-based scans, while a plain-list edge lookup costs O(degree). Edge lists suit Kruskal; CSR improves locality on large graphs.

Labels need not be dense array indices. Map labels to IDs or use dictionaries. Specify whether traversal reads an immutable snapshot; adjacency mutation can invalidate iteration. Distinguish vertices reachable from one root from processing all V.

A worked trace

Edges A–B andB–C produce A:[B], B:[A,C], C:[B]; E=2 but there are four adjacency entries.

Cost and assumptions

Lists O(V+E), matrices Θ(V²). Matrices may waste space on sparse graphs.

Executable example

Run with Python 3. Assertions check a small example; they do not constitute a general correctness proof. Some advanced examples are explicitly small models or reference oracles, not full production implementations.

Python 3
def undirected_graph(vertices, edges):
    g = {v: [] for v in vertices}
    for a, b in edges:
        g[a].append(b); g[b].append(a)
    return g
assert undirected_graph("ABC", [("A","B"),("B","C")])["B"] == ["A","C"]

TEST YOUR UNDERSTANDING

Your turn

Can zero denote a missing matrix edge when edges may have weight0?

Reveal the reasoning

No. Use None or a separate presence mask; missing and zero-cost edges differ.

Take it further

  1. Write down the input contract and the invariant before changing the example.
  2. Add empty, boundary, duplicate and adversarial cases where they are relevant. Compare with a simple oracle.
  3. Derive the cost under the stated model; measure several input sizes and explain discrepancies.

Primary reading & lecture notes

Original explanations in this course; these references provide proofs and further reading. Source links may cover the broader module.

MIT 6.006 · Introduction to Algorithms ↗
Solve the exercise before moving on.