Sub topic 2
Undirected graphs: symmetric relationships
This chapter covers the undirected graph, the simplest of the three graph types. It defines what makes an edge undirected, shows how that choice shows up in code, and lists the mistakes that most often break undirected graph code. It assumes you know what a vertex and an edge are, can use Python dictionaries and sets, and have a basic feel for big-O notation.
What "undirected" means
In an undirected graph, an edge connects two vertices without pointing from one to the other. Formally, an edge is an unordered pair {u, v}. The pair {A, B} and the pair {B, A} are the same edge, so if A is connected to B, then B is connected to A. The relationship is symmetric.
Use an undirected graph when the relationship is mutual by nature:
- Two people are friends on a network that requires both sides to accept.
- Two cities are joined by a two-way road.
- Two computers share a cable that carries traffic both ways.
- Two proteins physically bind to each other.
The test is simple. Ask whether "A relates to B" always implies "B relates to A" in the same way. If it does, an undirected graph fits. If it does not, as with "A follows B", you need a directed graph, which a later chapter covers.
The drawing has no arrowheads because direction carries no meaning. This graph has five vertices and four edges. It also has two clusters with no edge between them. Later chapters call these connected components.
Simple graphs and their limits
Most textbook treatments assume a simple graph. A simple graph has two restrictions:
- No self-loops. A self-loop is an edge from a vertex to itself, such as
{A, A}. - No parallel edges. Parallel edges are two or more separate edges between the same pair of vertices.
These restrictions give you a useful upper bound. With n vertices, each unordered pair of distinct vertices can be joined at most once. The number of such pairs is n * (n - 1) / 2, so a simple undirected graph has at most that many edges.
| Vertices (n) | Maximum edges |
|---|---|
| 4 | 6 |
| 10 | 45 |
| 100 | 4,950 |
A graph that reaches this maximum is called complete. A directed graph can have twice as many edges, because A -> B and B -> A are different edges.
Real data sometimes breaks the simple-graph rules. A road map can have two separate roads between the same towns, and a self-loop might model a vertex that links to itself. Whether you allow these is a modeling decision. The dictionary-based code below stores at most one edge per pair, so it cannot represent parallel edges. If you need them, you need a different structure, such as a list of edge objects.
Storing symmetry in code
An adjacency list stores, for each vertex, its neighbors. The chapter on adjacency lists covers this in detail. For now you only need one rule. An undirected edge must be stored in both directions, once under each endpoint.
This add_edge function follows that rule. It handles all three graph types through its parameters, but here you use its undirected default.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
undirected = {}
add_edge(undirected, "A", "B")
add_edge(undirected, "B", "C")
print(undirected) # {'A': {'B': 1}, 'B': {'A': 1, 'C': 1}, 'C': {'B': 1}}Each undirected edge produces two entries. The edge {A, B} appears as undirected["A"]["B"] and as undirected["B"]["A"]. The call to graph.setdefault(v, {}) makes sure that a vertex with no outgoing entries still appears as a key. Without it, a later graph[v] lookup would raise a KeyError.
Checking whether an edge exists is a dictionary lookup, which takes constant time on average:
def has_edge(graph, u, v):
return v in graph.get(u, {})
print(has_edge(undirected, "A", "B")) # True
print(has_edge(undirected, "B", "A")) # True
print(has_edge(undirected, "A", "C")) # FalseFor a correct undirected graph, has_edge(g, u, v) always equals has_edge(g, v, u). That equality is the symmetry invariant, and every function you write for undirected graphs relies on it.
Counting edges without counting twice
Because each edge is stored twice, the total number of inner-dictionary entries is twice the number of edges. This trips people up when they compute the edge count or list the edges. A naive loop over all neighbors reports every edge twice, once from each end.
The fix is to track which unordered pairs you have already reported. A frozenset works well here because frozenset(("A", "B")) equals frozenset(("B", "A")) and can be stored in a set.
def edges(graph):
seen = set()
result = []
for u in graph:
for v in graph[u]:
key = frozenset((u, v))
if key not in seen:
seen.add(key)
result.append((u, v))
return result
print(edges(undirected)) # [('A', 'B'), ('B', 'C')]
print(len(edges(undirected))) # 2This also handles self-loops correctly. For a loop on A, the key is frozenset(("A",)), which is reported once. A self-loop is stored as a single entry (graph["A"]["A"]), not two, so the "twice the entries" rule holds only for edges between distinct vertices.
Keeping the graph symmetric
The most common bug in undirected graph code is a half-stored edge. Suppose you write directly into the dictionary and update only one side:
broken = {"A": {"B": 1}, "B": {}}Here A lists B as a neighbor, but B does not list A. Any algorithm that assumes symmetry now gives inconsistent answers. A traversal started at A reaches B, while one started at B does not reach A. The data describes a directed graph that you meant as undirected.
A validator makes this kind of bug easy to catch during development:
def is_symmetric(graph):
for u in graph:
for v, w in graph[u].items():
if graph.get(v, {}).get(u) != w:
return False
return True
print(is_symmetric(undirected)) # True
print(is_symmetric(broken)) # FalseThe check compares weights as well as presence. In a weighted undirected graph, A -> B with weight 4 and B -> A with weight 7 would describe two different edges, which contradicts the model.
Common errors
- Forgetting the reverse entry. Symptoms are traversals that reach different vertices depending on the start, and
has_edge(g, u, v)disagreeing withhas_edge(g, v, u). - Double-counting edges. Summing neighbor-list lengths and reporting it as the edge count gives
2m, notm. Divide by two, or use a deduplicating function likeedges. - Treating a self-loop like a normal edge. A loop adds one entry, not two. Code that divides the entry count by two will miscount graphs that contain loops.
- Missing isolated vertices. A vertex with no edges must still be a key in the dictionary. If you only create keys when an edge is added, a vertex that never gets an edge disappears from the graph. Add such vertices explicitly with
graph.setdefault(v, {}). - Using tuples where order matters. Storing edges as
(u, v)tuples in a set makes("A", "B")and("B", "A")two distinct items. Usefrozensetor a sorted tuple to get one canonical form.
How undirected graphs relate to the other types
An undirected graph is a special case of a directed graph in which every edge has a partner pointing the opposite way. This is exactly how the dictionary representation works: it stores two directed entries for each undirected edge. Many algorithms written for directed graphs therefore work unchanged on undirected ones.
The reverse conversion loses information. If you drop direction from a directed graph, you can no longer tell which way each relationship ran.
Undirected graphs can also carry weights. A road network with distances on its edges is a weighted undirected graph. Weight and direction are independent choices, so a graph can be any of the four combinations.
Undirected graphs also set up two ideas that come later. Connectivity is simple to define when edges are symmetric, because "A can reach B" always implies "B can reach A". And a minimum spanning tree, covered at the end of this tutorial, is defined for weighted undirected graphs.
Exercise
An undirected graph has 5 vertices. Its adjacency list stores the neighbor lists A: [B, C], B: [A, C, D], C: [A, B], D: [B, E], E: [D]. How many edges does the graph have, and what would the entries look like if the edge {C, D} were added correctly?
Show answer
The neighbor lists hold 2 + 3 + 2 + 2 + 1 = 10 entries, and each edge is stored twice, so the graph has 5 edges: {A,B}, {A,C}, {B,C}, {B,D}, {D,E}. Adding {C, D} correctly means writing D into C's list and C into D's list, giving C: [A, B, D] and D: [B, E, C]. The graph then has 6 edges and 12 entries. Adding only one of the two entries would leave the graph asymmetric.
Exercise
A teammate counts edges with sum(len(graph[u]) for u in graph) on a graph that has no self-loops and gets 14. What is the real edge count, and what does the result become if exactly one vertex has a self-loop (stored as one entry) and the sum is still 14?
Show answer
With no self-loops, each edge contributes two entries, so the edge count is 14 / 2 = 7. With exactly one self-loop contributing one entry, the other 13 entries come from edges between distinct vertices. 13 is odd, so 13 / 2 is not a whole number, which means this scenario is impossible for a symmetric graph. A symmetric graph with one self-loop has an odd total entry count, such as 15, giving (15 - 1) / 2 + 1 = 8 edges. A sum of 14 with one self-loop signals a missing reverse entry somewhere.