Everyone knows everyone
Graphs as Friendship Maps
The analogy
A friendship map is messier than an org chart: friendship goes both ways, circles loop back on each other, and there is no single person at the top. A graph is just dots (people) joined by lines (relationships). And here is the family secret: the org chart from last lesson IS one of these โ a tree is simply a graph that happens to have no loops and one person at the top.
Visualizer
Dots, lines and loops
step 1 / 6Eight dots, ten lines. No root, no hierarchy โ just relationships.V = 8, E = 10
๐ In depth โ the full reference
The two representations
| aspect | adjacency LIST | adjacency MATRIX |
|---|---|---|
| memory | O(V + E) โ only real friendships stored | O(Vยฒ) โ every possible pair, mostly zeros |
| edge lookup uโv? | O(degree(u)) | O(1) โ matrix[u][v] |
| list all neighbours of u | O(degree(u)) โ already a list | O(V) โ scan the whole row |
| add edge | O(1) | O(1) |
| best for | sparse graphs (almost all real ones) | dense graphs, or O(1) edge tests |
Graph vocabulary you now own
- directed vs undirected (one-way vs mutual), weighted (edges carry costs โ Module 6 lives here), degree (edge count at a node).
- path (walk along edges), cycle (a path back to where you started), connected (everyone reachable from everyone).
- A tree is exactly the special case: connected, acyclic, one designated root โ every tree is a graph, not every graph is a tree.
- Facebook friendships: undirected. Twitter follows: directed. Flight prices: directed AND weighted. Your codebase's imports: directed, and you pray acyclic.
Python: dict of lists
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A"],
"D": ["B"],
}
print(len(graph["A"])) # degree of A โ O(1) lookup + O(1) len
print("D" in graph["B"]) # edge test โ O(degree)
# weighted variant: dict of dicts
costs = {"A": {"B": 5, "C": 2}}
print(costs["A"]["C"]) # 2 โ O(1) edge lookup, list AND matrix perksadj = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
}
len(adj["B"]) # degree of B
"C" in adj["A"] # is there an edge?
# space O(V + E) โ right for sparse graphsCheck yourself
A tree isโฆ
Practice โ write it yourself
degree_of(adj, node): adj is {"A": ["B","C"], ...}. Return how many friends (edges) the node has โ 0 if the node is unknown.
Python 3 ยท runs in your browser ยท your draft is saved locally
๐ My notessaved in this browser