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 / 6
ABCDEFGH

Eight dots, ten lines. No root, no hierarchy โ€” just relationships.V = 8, E = 10

๐Ÿ“– In depth โ€” the full reference

The two representations

aspectadjacency LISTadjacency MATRIX
memoryO(V + E) โ€” only real friendships storedO(Vยฒ) โ€” every possible pair, mostly zeros
edge lookup uโ€”v?O(degree(u))O(1) โ€” matrix[u][v]
list all neighbours of uO(degree(u)) โ€” already a listO(V) โ€” scan the whole row
add edgeO(1)O(1)
best forsparse 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 perks
adj = {
    "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 graphs
Check 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