Introduction to graphs
easy 18 minA graph is a set of vertices joined by edges, directed or undirected, weighted or not.
Video lesson · Chapter 1 of 7
Who can receive the message?
Graph fundamentals — The two-ferry shortcut
1:27Reel
Read caption
Kiko finds a route between two islands that look adjacent on a paper chart. Follow three ferry lines into an adjacency list. Dots are places. Lines are rides. A path is a chain of rides.
How it works
Step through the idea, or press Play.
Name the parts. Vertices are the things, edges are the connections between pairs of them
Understand it
Start here
What a graph is
A graph is a set of vertices (also called nodes) and a set of edges, each joining a pair of vertices. That is all. Unlike a list or a tree, there is no first item, no root and no fixed shape: anything can connect to anything, which is why graphs model so much of the real world.
The formal definition
Social networks
People are vertices, friendships are edges. "People you may know" is a question about neighbours of neighbours.
Maps and navigation
Junctions are vertices, roads are edges, and travel time is a weight on each edge.
Computer networks
Devices are vertices, cables and links are edges. Is the network still in one piece after a failure?
Dependencies
Tasks or courses are vertices, "must come before" is a directed edge. Build tools and schedulers live here.
Vocabulary
Vertices, edges, neighbours and degree
A triangle: three vertices, three edges
| Term | Meaning | In the triangle |
|---|---|---|
| Vertex (node) | A basic unit; it can carry data | A, B, C |
| Edge | A connection between two vertices | A-B, A-C, B-C |
| Adjacent / neighbour | Joined by one edge | B and C are neighbours of A |
| Degree | Number of edges touching | |
| Self-loop | An edge from a vertex to itself | none |
| Simple graph | No self-loops, no repeated edges | yes |
Edge types
Directed, undirected and weighted
Undirected
Edges go both ways. If A connects to B, B connects to A. Written or A — B. Example: Facebook friendships.
Directed (digraph)
Each edge is an arrow. does not mean . Written . Examples: Twitter follows, web links.
Weighted
Each edge carries a number: a distance, a cost, a time. Either kind of graph can be weighted.
A directed cycle and a weighted road map
Counting
Degree and the handshake lemma
Add up every vertex's degree and you always get twice the number of edges. Each edge has two ends and adds 1 to the degree of each, so it is counted exactly twice. It is called the handshake lemma because at a party the total of everyone's handshake counts is twice the number of handshakes.
Handshake lemma (undirected)
Directed version: in-degree and out-degree
Limits
How many edges can a graph have?
Maximum edges in a simple graph
| Kind | Edges | Example | Best representation |
|---|---|---|---|
| Sparse | close to | Road maps, social networks, the web | Adjacency list |
| Dense | close to | Small complete graphs, flight tables | Matrix is fine |
| Tree | exactly | File systems, org charts | Adjacency list |
| Complete | Every pair of cities joined | Matrix |
Structure
Paths, cycles and connected components
| Term | Meaning |
|---|---|
| Path | A sequence of vertices where each consecutive pair is joined by an edge. Its length is the number of edges. |
| Simple path | A path that never repeats a vertex. |
| Cycle | A path of length 3 or more that starts and ends at the same vertex without reusing an edge. |
| Connected | Every vertex can reach every other by some path (undirected). |
| Connected component | A maximal group of vertices that can all reach each other. |
| Strongly connected | Directed version: every vertex can reach every other following the arrows. |
One graph, two connected components
Special shapes
Trees and DAGs are graphs too
Tree
Connected and no cycles. Always exactly edges, and exactly one path between any two vertices. See binary tree.
DAG
Directed acyclic graph: arrows, no directed cycle. Models task scheduling and course prerequisites; it has a topological order.
Bipartite
Vertices split into two sides with every edge crossing between them, so two colours suffice. Used for matching problems.
Implicit graph
A grid is a graph: each cell is a vertex, its up, down, left and right cells are its edges. See matrix DFS.
Tree test
Course prerequisites form a DAG
Representations
Three ways to store a graph
| Representation | The square graph 0-1, 0-2, 1-3, 2-3 | Space |
|---|---|---|
| Edge list | [(0,1), (0,2), (1,3), (2,3)] | |
| Adjacency list | 0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2] | |
| Adjacency matrix | [[0,1,1,0], [1,0,0,1], [1,0,0,1], [0,1,1,0]] |
From input to something you can walk
edges = [(0, 1), (0, 2), (1, 3), (2, 3)]n = 4# 1. Edge list: the input itselfprint("Edge list:", edges)# 2. Adjacency list: O(V + E) spaceadj = [[] for _ in range(n)]for u, v in edges: adj[u].append(v) adj[v].append(u) # undirected: both directionsprint("Adjacency list:")for i, nbs in enumerate(adj): print(f" {i}: {nbs}")# 3. Adjacency matrix: O(V^2) spacematrix = [[0] * n for _ in range(n)]for u, v in edges: matrix[u][v] = 1 matrix[v][u] = 1 # symmetricprint("Adjacency matrix:")for row in matrix: print(" ", row)print("has edge 1-3?", matrix[1][3] == 1, 3 in adj[1])print("degrees:", [len(nbs) for nbs in adj]) # [2, 2, 2, 2]Costs
Adjacency list versus matrix
Where the space goes
| Operation | Adjacency list | Adjacency matrix | Note |
|---|---|---|---|
| Space | List wins on sparse graphs | ||
| Add vertex | Matrix must be rebuilt one size bigger | ||
| Add edge | Both constant | ||
| Has edge | Neighbour sets make the list average | ||
| Get neighbours of | to fetch, to walk | Matrix scans a full row | |
| Remove edge | List searches both lists | ||
| Remove vertex | Both expensive | ||
| Full DFS / BFS | Why interviews use lists |
Use an adjacency list when
- The graph is sparse, much smaller than (nearly always).
- You iterate neighbours, as every BFS and DFS does.
- Memory matters or is large.
- The input is an edge list, as in most interview problems.
Use an adjacency matrix when
- The graph is small or dense, close to .
- You need many "is there an edge?" checks.
- The algorithm is matrix-shaped, like Floyd-Warshall all-pairs shortest paths.
- Weights fit naturally in cells,
matrix[u][v] = w.
Traversal
Walking a graph: DFS and BFS with a visited set
The two traversals you know from trees work on graphs with one addition: a visited set. A tree has no cycles, so you never meet a node twice; a graph can lead you back to where you started. Tree DFS dives deep along one path, tree BFS spreads out ring by ring, and the grid versions are matrix DFS and matrix BFS.
The traversal loop with a visited set
from collections import dequeedges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 3), (3, 4)]adj = [[] for _ in range(5)]for u, v in edges: adj[u].append(v) adj[v].append(u)def dfs(u, visited, order): visited.add(u) order.append(u) for v in adj[u]: if v not in visited: # without this: infinite recursion dfs(v, visited, order) return orderdef bfs(start): visited, queue, order = {start}, deque([start]), [] while queue: u = queue.popleft() order.append(u) for v in adj[u]: if v not in visited: visited.add(v) # mark when enqueued queue.append(v) return orderprint("DFS:", dfs(0, set(), [])) # [0, 1, 3, 2, 4]print("BFS:", bfs(0)) # [0, 1, 2, 3, 4]| DFS (depth-first) | BFS (breadth-first) | |
|---|---|---|
| Container | Stack or recursion | Queue (deque) |
| Order | Goes deep before wide | Goes wide before deep |
| Good for | Paths, cycles, components, topological sort | Fewest edges, nearest target, levels |
| Time | ||
| Extra space | visited plus up to recursion | visited plus up to queue |
Pattern spotting
Recognising a graph problem
- 1Read n and edgesDirected? Weighted?
- 2Build adjacency listBoth directions if undirected
- 3Pick a traversalDFS, BFS or Dijkstra
- 4Visit with a setEach vertex once
- 5Loop all verticesCover every component
Steps 2 and 4 are the same in nearly every problem; the thinking goes into step 3 and what you record while visiting.
| Clue in the problem | Graph view | Example problems |
|---|---|---|
| "connections", "friends", "network" | Undirected graph, count components | Number of provinces, connected components |
| "depends on", "prerequisite", "before" | Directed graph, detect cycles, topological sort | Course schedule, task order |
| Grid of land and water | Implicit graph, 4-directional neighbours | Number of islands, flood fill |
| "fewest steps", "minimum moves" | Unweighted graph, BFS | Word ladder, open the lock |
| "cheapest", "fastest", costs on edges | Weighted graph, Dijkstra | Network delay time |
| Copy or serialise a graph | Traversal plus old-to-new map | Clone graph |
Which traversal?
Recap
Key takeaways
Key points
- A graph is vertices plus edges. Edges can be directed or undirected, weighted or unweighted.
- Degree counts a vertex's edges, and ; in a digraph in-degrees and out-degrees each sum to .
- A simple graph has at most undirected or directed edges. Real graphs are usually sparse.
- Trees (connected, acyclic, edges), DAGs and grids are all special graphs.
- Adjacency list: space and neighbours, the default. Matrix: space and edge checks, for small dense graphs.
- DFS and BFS on a graph need a visited set; both run in on an adjacency list. Start a new traversal from every unvisited vertex to cover all components.