Python 3D Academyবাংলা

Vertices and edges; adjacency lists and matrices

🌍 In real life. A map of six towns and the roads between them. A school's friendships: who is friends with whom, and the friends of your friends. The links between web pages. None of these is a list, and none is a tree: a town can have roads to many others, and you can drive round in a circle.

That shape is a graph: things, and links between pairs of them. Trees (Chapters 47–50) were special graphs with one path to each node; from here on, anything can link to anything. This chapter stores graphs and walks them; the next four chapters solve problems on them.

The idea in one sentence: a graph is a set of vertices joined by edges, and a program usually stores it as an adjacency list (each vertex with the list of its neighbours) or an adjacency matrix (a grid of 0s and 1s saying which pairs are joined).

Its words:

  • vertex (also node): one thing, here a town
  • edge: a link between two vertices, here a road
  • undirected / directed: a road you can drive both ways, or a one-way street (Chapter 52)
  • neighbours: the vertices joined to a vertex by an edge; their number is its degree
  • path: a sequence of vertices, each joined to the next; a cycle is a path back to where it started
  • connected: every vertex can be reached from every other
  • adjacency list: in Python, a dict from each vertex to a list of its neighbours
  • adjacency matrix: a V × V table where row i, column j is 1 if vertices i and j are joined

How to build an adjacency list, step by step:

  1. start with an empty dict
  2. for each edge a–b: add b to a's list and a to b's list (an undirected edge goes both ways)
  3. sort each list, so the neighbours always come in the same order

Watch the list for six towns fill one row at a time:

Why it is correct. Each edge a–b is a fact about two vertices, so it belongs in both of their lists, and building from every edge once puts every neighbour in place exactly once. The matrix records the same facts as a table: it is symmetric for an undirected graph (row a, column b equals row b, column a), and its row for a vertex has a 1 for each neighbour.

What it costs, by counting. With V vertices and E edges:

  • the adjacency list holds 2E entries (each edge from both ends) plus V lists: O(V + E) memory; checking whether a and b are joined means scanning a's list, O(degree)
  • the matrix always holds V × V cells: O(V²) memory; checking a pair is one lookup, O(1)

Real graphs are usually sparse, with far fewer edges than V². For 1,000 towns with 3,000 roads, the lists hold about 6,000 entries (2 × 3,000, in 1,000 lists) but the matrix 1,000,000 cells, almost all 0. So the adjacency list is the usual choice, and the matrix is for small or dense graphs.

def build_adjacency(edges):
    graph = {}
    for a, b in edges:
        graph.setdefault(a, []).append(b)   # a road works both ways,
        graph.setdefault(b, []).append(a)   # so list it from both ends
    for v in graph:
        graph[v].sort()
    return graph

roads = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"), ("C", "E"), ("D", "F")]
graph = build_adjacency(roads)
for town in sorted(graph):
    print(town, graph[town], "degree", len(graph[town]))

def to_matrix(vertices, edges):
    index = {v: i for i, v in enumerate(vertices)}
    m = [[0] * len(vertices) for _ in vertices]
    for a, b in edges:
        m[index[a]][index[b]] = 1
        m[index[b]][index[a]] = 1
    return m

for row in to_matrix(["A", "B", "C", "D", "E", "F"], roads):
    print(row)

Mistakes and edge cases.

  • adding an undirected edge one way only: then B can reach A but A doesn't know about B, and searches miss half the graph
  • a vertex with no edges: it never appears in an edge list, so build_adjacency doesn't know it exists; add every vertex first if some may be alone
  • [[0] * n] * n for the matrix: that makes n references to the same row, so setting one cell sets the whole column; build each row separately
  • listing an edge twice: the neighbour appears twice in the list; use a set while building if the input may repeat
  • unsorted neighbour lists: the graph is the same, but searches visit vertices in a different order; sorting keeps results repeatable

Quiz

  1. What does this print?

    def build_adjacency(edges):
        graph = {}
        for a, b in edges:
            graph.setdefault(a, []).append(b)   # a road works both ways,
            graph.setdefault(b, []).append(a)   # so list it from both ends
        for v in graph:
            graph[v].sort()
        return graph
    
    g = build_adjacency([("A", "B"), ("B", "C"), ("C", "A"), ("C", "D")])
    print(g["C"], len(g["D"]))
  2. An undirected graph has 100 vertices and 250 edges. How many entries does its adjacency list hold in all?

    • 500: each edge is listed from both ends
    • 250
    • 10,000
  3. When is an adjacency matrix the better choice?

    • For a small or dense graph where you often ask "are a and b joined?"
    • For a huge graph with few edges
    • Never: lists are always better
  4. After m[0][1] = 1, every row shows a 1 in column 1. Which line is wrong?

    n = 3
    m = [[0] * n] * n
    m[0][1] = 1
    print(m)
  5. Friends of friends. What does this print?

    graph = {"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"], "D": ["B", "C", "F"], "E": ["C"], "F": ["D"]}
    def mutual_friends(graph, a, b):
        return sorted(set(graph[a]) & set(graph[b]))
    
    print(mutual_friends(graph, "B", "C"), mutual_friends(graph, "E", "F"))

Coding tasks

  1. Write build_adjacency(edges): edges is a list of pairs (a, b), each an undirected edge. Return a dict from each vertex to the sorted list of its neighbours.

  2. Write to_matrix(vertices, edges): the adjacency matrix as a list of rows, in the order of vertices; row i, column j is 1 if vertices i and j are joined by an undirected edge, else 0.

  3. Friends of friends. Write mutual_friends(graph, a, b): the vertices joined to both a and b, as a sorted list. graph is an adjacency-list dict.