Graphs Intro
A graph is a set of vertices (also called nodes) connected by edges. Trees are a special kind of graph, but general graphs may contain cycles, may be disconnected, and have no root. Graphs model anything made of things and the connections between them:
| Domain | Vertices | Edges |
|---|---|---|
| Road map | intersections, cities | roads (with distances) |
| Social network | people | friendships or "follows" |
| The web | pages | links |
| Course planning | courses | "must be taken before" |
| Computer networks | routers | cables (with capacities) |
Kinds of graphs
Undirected vs directed. In an undirected graph an edge A - B can be travelled both ways (friendship). In a directed graph, or digraph, an edge A -> B goes one way only (following someone, a one-way street, a prerequisite).
Unweighted vs weighted. A weighted graph attaches a number to every edge: a distance, a cost, a time, a capacity.
Connected vs disconnected. An undirected graph is connected if there is a path between every pair of vertices.
Cyclic vs acyclic. A cycle is a path that returns to its start without reusing an edge. A directed graph without cycles is a DAG (directed acyclic graph), the shape of task dependencies and spreadsheets.
Here is a small undirected graph. The animation explores it from A with breadth-first search; you'll learn exactly how in the Graph Traversal lesson. For now, notice how the search spreads out from A along the edges:
Vocabulary
| Term | Meaning |
|---|---|
| Adjacent (neighbours) | two vertices joined by an edge |
| Degree | number of edges at a vertex (directed: in-degree and out-degree) |
| Path | a sequence of vertices where each consecutive pair is joined by an edge |
| Path length | number of edges (unweighted) or the sum of the weights |
| Cycle | a path that starts and ends at the same vertex |
| Connected component | a maximal group of vertices that are all reachable from each other |
A graph in Python
The simplest way to store a graph in Python is a dictionary that maps each vertex to the list of its neighbours, an adjacency list:
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "D"],
"D": ["B", "C", "E"],
"E": ["D"],
}
edges = sum(len(neighbours) for neighbours in graph.values()) // 2 # each edge counted twice
print("vertices:", len(graph), "edges:", edges)
for v, neighbours in graph.items():
print(f"{v}: degree {len(neighbours)}, neighbours {neighbours}")vertices: 5 edges: 5
A: degree 2, neighbours ['B', 'C']
B: degree 2, neighbours ['A', 'D']
C: degree 2, neighbours ['A', 'D']
D: degree 3, neighbours ['B', 'C', 'E']
E: degree 1, neighbours ['D']
The sum of all degrees is always twice the number of edges, because each edge touches two vertices (the handshake lemma).
Directed and weighted graphs
For a directed graph, store only the outgoing edges. For a weighted graph, store (neighbour, weight) pairs or a nested dictionary:
# who follows whom (directed)
follows = {"ana": ["ben", "cleo"], "ben": ["cleo"], "cleo": ["ana"], "dev": ["ana"]}
in_degree = {person: 0 for person in follows}
for person, targets in follows.items():
for t in targets:
in_degree[t] += 1
print("followers:", in_degree)
# travel times in minutes (weighted, undirected)
roads = {
"Home": {"Park": 7, "Shop": 3},
"Park": {"Home": 7, "School": 4},
"Shop": {"Home": 3, "School": 9},
"School": {"Park": 4, "Shop": 9},
}
route = ["Home", "Park", "School"]
minutes = sum(roads[a][b] for a, b in zip(route, route[1:]))
print(" -> ".join(route), "takes", minutes, "minutes")followers: {'ana': 2, 'ben': 1, 'cleo': 2, 'dev': 0}
Home -> Park -> School takes 11 minutes
Home → Park → School takes 11 minutes, while Home → Shop → School takes 12. Finding the best route automatically is the shortest path problem, solved by Dijkstra's algorithm later in this course.
Graph algorithms in this course
| Problem | Algorithm | Lesson |
|---|---|---|
| Visit every reachable vertex | BFS, DFS | Graph Traversal |
| Does the graph contain a cycle? | DFS, union-find | Cycle Detection |
| Order tasks by their dependencies | Kahn's algorithm, DFS | Topological Sort |
| Cheapest route | Dijkstra, Bellman-Ford | Shortest Path |
| Cheapest way to connect everything | Prim, Kruskal | Minimum Spanning Tree |
| How much can flow through a network? | Ford-Fulkerson, Edmonds-Karp | Maximum Flow |
| Shortest round trip through all cities | brute force, heuristics | The Traveling Salesman |
Test yourself
Which kind of graph fits "user X follows user Y"?
- Undirected
- Directed
- A tree
- Weighted only
An undirected graph has vertices with degrees 3, 2, 2 and 1. How many edges does it have?
- 2
- 4
- 8
- Impossible to tell
What is a DAG?
- A graph with weights
- A directed graph with no cycles
- A disconnected graph
- A graph with only two vertices