Sub topic 1
What a graph is: vertices and edges
Prerequisites
This chapter assumes you can write basic Python with lists, dictionaries, and sets. It also assumes you know introductory Big-O notation. You do not need to know any graph theory.
The definition
A graph is a pair of sets, G = (V, E). V is a set of vertices (also called nodes). E is a set of edges, where each edge connects two vertices. Vertices stand for things. Edges stand for relationships between those things.
Many problems fit this shape:
- Cities are vertices and roads are edges.
- People are vertices and friendships are edges.
- Web pages are vertices and links are edges.
- Tasks are vertices and "must happen before" rules are edges.
The graph keeps only the structure: which things are related. It does not record where a vertex sits on a page or how long a drawn line is. Two drawings that connect the same vertices in the same way show the same graph.
A first example
Take four vertices, A, B, C and D, and four edges: A-B, A-C, B-D and C-D.
In code, the simplest way to write this graph is a list of vertex pairs.
vertices = {"A", "B", "C", "D"}
edges = [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D")]
print(len(vertices)) # 4 vertices
print(len(edges)) # 4 edgesThis list of pairs is called an edge list. A later chapter compares it with other storage choices. For now, treat it as a way to write down a graph exactly.
Edges can have direction
In an undirected graph, an edge is a two-way relationship. If A-B is an edge, you can go from A to B and from B to A. Friendship on a social network that requires both people to agree is undirected.
In a directed graph, each edge has a start and an end. The edge A → B lets you go from A to B but says nothing about going back. Following someone on a service that does not require a follow back is directed.
In code, a pair ("A", "B") is read as "from A to B" when the graph is directed. In an undirected graph, ("A", "B") and ("B", "A") describe the same edge. This difference matters whenever you check whether an edge exists, so decide it before you write any code.
directed = [("A", "B"), ("B", "C")]
undirected = {frozenset(("A", "B")), frozenset(("B", "C"))}
print(("B", "A") in directed) # False
print(frozenset(("B", "A")) in undirected) # TrueA frozenset has no order, so {"A", "B"} equals {"B", "A"}. That makes it a convenient way to store an undirected edge as one item.
Edges can carry a weight
A weighted graph attaches a number to each edge. The number might be a distance, a cost, or a time. An unweighted graph has no such numbers, so every edge counts the same.
weighted = {("A", "B"): 4, ("A", "C"): 1, ("C", "B"): 2}
print(weighted[("A", "B")]) # 4Weights change which questions are interesting. In an unweighted graph, the shortest path is the one with the fewest edges. In a weighted graph, it is the one with the smallest total weight, which can use more edges.
Common mistakes
- Mixing up directed and undirected storage. If you store an undirected edge once, a lookup for the reversed pair fails.
- Forgetting isolated vertices. A vertex with no edges never appears in an edge list. Keep the vertex set separately if such vertices matter.
- Assuming weights mean distance. A weight is only a number. It can be a cost, a capacity, or even negative. Check which meaning your problem uses.
Check your understanding
Exercise
A route planner stores one-way streets and the length of each street in meters. Is its graph directed or undirected, and weighted or unweighted? What would a vertex and an edge be?
Show answer
The graph is directed, because a one-way street can be driven in only one direction, and weighted, because each street has a length. A vertex is an intersection. An edge is a street segment from one intersection to the next, carrying its length in meters as the weight.
Exercise
Given edges = [("A", "B"), ("C", "D")] for an undirected graph with vertices A, B, C, D, E, how many vertices and edges does the graph have, and why can you not find E from the edge list alone?
Show answer
It has 5 vertices and 2 edges. E has no edges, so it appears in no pair. You need a separate vertex set to know it exists.