Sub topic 1
What a graph is: vertices and edges
Prerequisites
This chapter assumes you can do the following:
- Write basic Python with lists, dictionaries, sets, and functions.
- Read simple big-O notation such as O(1), O(n), and O(n + m).
- Use a queue and a stack as data structures.
It does not assume any prior graph theory. Later chapters build on the vocabulary introduced here.
What a graph is
A graph is a set of things and a set of connections between them. The things are called vertices (singular: vertex, also called nodes). The connections are called edges (also called links or arcs).
Formally, a graph is a pair G = (V, E):
- V is a finite set of vertices.
- E is a set of edges, where each edge connects two vertices from V.
If a graph has four vertices named A, B, C, and D, then V = {A, B, C, D}. If A connects to B and B connects to C, then E contains those two connections. Vertex D has no edges. That is still a valid graph.
Two sizes appear in nearly every cost estimate in this tutorial. By convention, n is the number of vertices, written |V|, and m is the number of edges, written |E|. When you see a cost such as O(n + m), it means the work grows with both the vertices and the edges.
Why graphs matter
A graph models relationships, and many problems are relationship problems in disguise. The table shows how common situations map onto vertices and edges.
| Situation | Vertices | Edges | Question you might ask |
|---|---|---|---|
| Social network | People | Friendships | How many hops separate two people? |
| Road map | Intersections | Road segments | What is the shortest route? |
| Web | Pages | Hyperlinks | Which pages can I reach from here? |
| Build system | Tasks | "Must run before" rules | In what order can tasks run? |
| Computer network | Machines | Cables | Does one failed cable split the network? |
The skill in graph work is choosing the model. You decide what a vertex is, what an edge means, and whether edges need a direction or a value. Those three choices lead to the three graph types in this tutorial.
Three questions that pick the graph type
Ask these questions about each relationship in your problem.
- Is the relationship symmetric? If A is related to B, is B always related to A? Friendship on most social networks is symmetric. Following someone is not. Symmetric relationships give an undirected graph. One-way relationships give a directed graph.
- Does the relationship carry a number? Distance, cost, capacity, or time attach a value to the edge. That gives a weighted graph.
- Can the same pair be connected more than once, or can a vertex connect to itself? This decides whether you allow parallel edges and self-loops.
The first two questions are independent. A graph can be directed and weighted, or undirected and weighted. The next chapters take each type in turn. Here we fix the shared foundation.
Edges, endpoints, and adjacency
An edge joins two vertices, called its endpoints. If the edge joins u and v, we say the edge is incident to both of them. We also say u and v are adjacent, or that v is a neighbor of u.
Adjacency is the idea that the rest of the tutorial relies on. Almost every graph algorithm asks the same question again and again: given a vertex, who are its neighbors?
Edge notation depends on the graph type:
- In an undirected graph, an edge is written {u, v}. The order does not matter, so {A, B} and {B, A} are the same edge.
- In a directed graph, an edge is written (u, v). The order matters, so (A, B) and (B, A) are different edges.
Simple graphs, self-loops, and parallel edges
Most textbook algorithms assume a simple graph. A simple graph has no self-loops and no parallel edges.
- A self-loop is an edge from a vertex to itself, such as {A, A}.
- Parallel edges (also called multi-edges) are two or more edges between the same pair of vertices.
A graph that allows parallel edges is a multigraph. Real data often contains them. Two cities can be joined by both a highway and a rail line. A bank account can send several payments to the same recipient.
This matters for the edge limit. In a simple undirected graph with n vertices, each pair of vertices has at most one edge. The number of pairs is n(n − 1) / 2, so:
- m is at most n(n − 1) / 2 for a simple undirected graph.
- m is at most n(n − 1) for a simple directed graph, because each ordered pair can have an edge.
A graph with close to the maximum number of edges is dense. A graph with far fewer, closer to n than to n², is sparse. Dense and sparse are informal terms, but they drive the choice of data structure in a later chapter.
Modeling a graph in Python
A simple way to store a graph in Python is a dictionary. Each key is a vertex. Each value holds that vertex's neighbors. This is an adjacency list, and a later chapter covers it in detail. We use it now so you can run code from the start.
graph = {
"A": {"B"},
"B": {"A", "C"},
"C": {"B"},
"D": set(),
}
def neighbors(graph, u):
return graph[u]
def vertex_count(graph):
return len(graph)
def edge_count(graph):
# Each undirected edge appears twice, once from each endpoint.
return sum(len(nbrs) for nbrs in graph.values()) // 2
print(neighbors(graph, "B") == {"A", "C"}) # True
print(vertex_count(graph)) # 4
print(edge_count(graph)) # 3 would be wrong; see belowRun this and the last line prints 2, not 3. The graph has two edges, {A, B} and {B, C}. The diagram above also shows two edges. The comment in the code is a deliberate trap, so check your own count before trusting a comment. Here is the corrected version of that last line.
print(edge_count(graph)) # 2The division by 2 works only because the graph is undirected and every edge is stored in both directions. For a directed graph you would not divide. The next two chapters show why.
Common errors
These mistakes appear often when people first model data as a graph.
- Forgetting isolated vertices. If you build the dictionary only from edges, a vertex with no edges never gets a key. Later,
graph[u]raises aKeyError. Add every vertex, even if it has no neighbors. - Counting each undirected edge twice. In an adjacency list, an undirected edge appears under both endpoints. Summing the neighbor counts gives 2m, not m.
- Confusing the edge limit for directed and undirected graphs. The limit n(n − 1) / 2 applies only to simple undirected graphs.
- Assuming no self-loops. If your data can contain them, a vertex can be its own neighbor. Code that assumes otherwise may loop forever or skip valid results.
- Modeling the wrong thing as a vertex. If you want to ask questions about the relationships themselves, such as flights between airports, decide whether the flight or the airport should be the vertex before you write any code.
A worked modeling example
Suppose you manage a small office with five people: Ana, Ben, Cy, Di, and Eli. Ana works with Ben. Ben works with Cy. Di works with Eli. You want to know whether Ana and Eli can reach each other through chains of coworkers.
- Vertices: the five people.
- Edges: "works with". This is symmetric, so the graph is undirected.
- No numbers are needed, so the graph is unweighted.
people = ["Ana", "Ben", "Cy", "Di", "Eli"]
works_with = [("Ana", "Ben"), ("Ben", "Cy"), ("Di", "Eli")]
office = {person: set() for person in people}
for a, b in works_with:
office[a].add(b)
office[b].add(a)
print(office["Ben"] == {"Ana", "Cy"}) # True
print(sum(len(n) for n in office.values()) // 2) # 3The office graph has five vertices and three edges. Ana and Eli sit in different groups with no chain between them. A later chapter on connectivity will make that precise. The key step here was the modeling, which took three sentences and no algorithm.
Summary of key terms
| Term | Meaning |
|---|---|
| Vertex (node) | A thing in the graph |
| Edge (link) | A connection between two vertices |
| Endpoints | The two vertices an edge joins |
| Adjacent | Joined by an edge |
| Neighbor | A vertex adjacent to a given vertex |
| Self-loop | An edge from a vertex to itself |
| Parallel edges | Several edges between the same pair |
| Simple graph | No self-loops and no parallel edges |
| Sparse / dense | Few edges / many edges relative to n² |
Exercise
A simple undirected graph has 6 vertices. What is the largest number of edges it can have? If you store it as a dictionary of neighbor sets, what do the neighbor-set sizes sum to when it has that many edges?
Show answer
The maximum is 6 × 5 / 2 = 15 edges. Each undirected edge is stored under both endpoints, so the neighbor-set sizes sum to 2 × 15 = 30.
Exercise
A streaming site records which users have watched which shows. You want to ask which users share a show. Name one possible choice of vertices and edges, and say whether the graph is directed.
Show answer
One choice: vertices are users and shows, and an edge joins a user to each show they watched. Watching is a relationship from a user to a show, but you can treat it as undirected because the question is about shared connections, not direction. Two users share a show if both are adjacent to the same show vertex. A different valid choice is vertices as users only, with an edge between two users who watched a common show.