Graph implementations
Storing a graph: an interface for graphs, adjacency matrices, edge lists, and adjacency lists compared by space and time, directed graphs, graphs of named vertices, and a paths API built on DFS and BFS.
- CS61B
- Graph Traversals and Implementations · Textbook Ch. 20
- Swift book
- Collection Types
- Documentation
- Dictionary · Set
Lesson 43 stored graphs as dictionaries of arrays and did not worry about the cost. CS61B’s next lecture does: how a graph is stored decides how fast every algorithm on it runs. This lesson compares the standard representations, designs a small graph interface, and builds the paths API that Project 9 uses.
An interface
Most graph algorithms need only a few things from a graph: how many vertices there are, and the neighbors of each. Following CS61B, vertices are the integers 0 to V − 1, and names, when needed, are mapped to numbers separately:
protocol Graph {
var vertexCount: Int { get }
var edgeCount: Int { get }
func neighbors(of v: Int) -> [Int]
}
An algorithm written against this protocol works with any representation, so the representation can be chosen for the graph’s shape.
Three representations
Adjacency matrix. A V × V table of booleans: entry (v, w) says whether there is an edge from v to w. Checking an edge takes constant time, but listing v’s neighbors means scanning a whole row, Θ(V), and the table takes Θ(V²) memory whatever the number of edges.
Edge list. Just a list of (v, w) pairs. Θ(E) memory, but finding a vertex’s neighbors means scanning every edge.
Adjacency lists. For each vertex, an array of its neighbors. Θ(V + E) memory, and listing v’s neighbors takes time proportional to its degree. This is the representation almost every graph algorithm assumes.
| Representation | Memory | Edge v–w? | Neighbors of v | DFS or BFS |
|---|---|---|---|---|
| Adjacency matrix | Θ(V²) | Θ(1) | Θ(V) | Θ(V²) |
| Edge list | Θ(E) | Θ(E) | Θ(E) | Θ(V · E) |
| Adjacency lists | Θ(V + E) | Θ(degree) | Θ(degree) | Θ(V + E) |
Real graphs are usually sparse: a road network or the web has far fewer edges than V², so adjacency lists win. For a million vertices, a matrix needs a trillion entries.
struct AdjacencyListGraph {
private(set) var adjacent: [[Int]]
private(set) var edgeCount = 0
let isDirected: Bool
init(vertices: Int, directed: Bool = false) {
adjacent = Array(repeating: [], count: vertices)
isDirected = directed
}
var vertexCount: Int { adjacent.count }
mutating func addEdge(_ v: Int, _ w: Int) {
adjacent[v].append(w)
if !isDirected {
adjacent[w].append(v)
}
edgeCount += 1
}
func neighbors(of v: Int) -> [Int] {
adjacent[v]
}
func degree(of v: Int) -> Int {
adjacent[v].count
}
}
var g = AdjacencyListGraph(vertices: 5)
for (v, w) in [(0, 1), (0, 2), (1, 2), (3, 4)] {
g.addEdge(v, w)
}
var d = AdjacencyListGraph(vertices: 3, directed: true)
d.addEdge(0, 1)
d.addEdge(1, 2)
print(g.neighbors(of: 2), g.degree(of: 0), g.edgeCount, d.neighbors(of: 1), d.neighbors(of: 2))
// [0, 1] 2 4 [2] []
An undirected edge is stored twice, once in each vertex’s list; a directed edge once, in its source’s list. The sum of all degrees in an undirected graph is therefore 2E.
What would Swift print?
var matrix = Array(repeating: Array(repeating: false, count: 4), count: 4)
for (v, w) in [(0, 1), (1, 2), (2, 0), (2, 3)] {
matrix[v][w] = true
}
let outDegrees = matrix.map { $0.filter { $0 }.count }
let inDegrees = (0..<4).map { w in (0..<4).filter { matrix[$0][w] }.count }
print(outDegrees, inDegrees)Show answer and explanation
Answer[1, 1, 2, 0] [1, 1, 1, 1]
In a directed graph’s matrix, row v lists v’s outgoing edges and column w lists w’s incoming edges. Vertex 2 has two edges out; every vertex has one edge in. Counting a column takes Θ(V) with a matrix; with adjacency lists it would need a scan of every list.
Named vertices
Real graphs have names: words, cities, web pages. A symbol graph keeps a dictionary from names to numbers and an array from numbers back to names, and stores the edges between numbers:
struct SymbolGraph {
private(set) var index: [String: Int] = [:]
private(set) var names: [String] = []
private var adjacent: [[Int]] = []
mutating func vertex(_ name: String) -> Int {
if let v = index[name] { return v }
index[name] = names.count
names.append(name)
adjacent.append([])
return names.count - 1
}
mutating func addEdge(_ a: String, _ b: String) {
let (v, w) = (vertex(a), vertex(b))
adjacent[v].append(w)
adjacent[w].append(v)
}
func neighbors(of name: String) -> [String] {
guard let v = index[name] else { return [] }
return adjacent[v].map { names[$0] }
}
}
var flights = SymbolGraph()
flights.addEdge("SFO", "JFK")
flights.addEdge("SFO", "TPE")
flights.addEdge("TPE", "NRT")
print(flights.neighbors(of: "SFO"), flights.neighbors(of: "NRT"), flights.names.count)
// ["JFK", "TPE"] ["TPE"] 4
The algorithms still work on integers, and names are converted only at the edges of the program. Project 9’s WordNet maps words to numbered groups of synonyms in exactly this way.
A paths API
CS61B separates what a client asks from how paths are found. A paths object is built once from a graph and a source, and then answers questions:
struct AdjacencyListGraph {
private(set) var adjacent: [[Int]]
init(vertices: Int) { adjacent = Array(repeating: [], count: vertices) }
mutating func addEdge(_ v: Int, _ w: Int) { adjacent[v].append(w); adjacent[w].append(v) }
func neighbors(of v: Int) -> [Int] { adjacent[v] }
var vertexCount: Int { adjacent.count }
}
struct BreadthFirstPaths {
private var edgeTo: [Int?]
private var distance: [Int?]
let source: Int
init(_ graph: AdjacencyListGraph, from source: Int) {
self.source = source
edgeTo = Array(repeating: nil, count: graph.vertexCount)
distance = Array(repeating: nil, count: graph.vertexCount)
distance[source] = 0
var queue = [source]
var head = 0
while head < queue.count {
let v = queue[head]
head += 1
for w in graph.neighbors(of: v) where distance[w] == nil {
distance[w] = distance[v]! + 1
edgeTo[w] = v
queue.append(w)
}
}
}
func hasPath(to v: Int) -> Bool { distance[v] != nil }
func distance(to v: Int) -> Int? { distance[v] }
func path(to v: Int) -> [Int]? {
guard hasPath(to: v) else { return nil }
var path = [v]
while let previous = edgeTo[path.last!] {
path.append(previous)
}
return path.reversed()
}
}
var g = AdjacencyListGraph(vertices: 7)
for (v, w) in [(0, 1), (1, 2), (2, 3), (0, 4), (4, 3), (5, 6)] {
g.addEdge(v, w)
}
let paths = BreadthFirstPaths(g, from: 0)
print(paths.path(to: 3)!, paths.distance(to: 3)!, paths.hasPath(to: 6)) // [0, 4, 3] 2 false
The expensive work, the search, happens once in the initializer. After that,
each question costs only as much as its answer: hasPath and distance are
constant time, and path is proportional to the path’s length. A client that
asks about many destinations from the same source pays for one search.
Put the lines in order
Put the lines in order so the program prints [[1], [0, 2], [1]].
var adjacent: [[Int]] = [[], [], []]adjacent[v].append(w)adjacent[w].append(v)}print(adjacent)for (v, w) in [(0, 1), (1, 2)] {
Show the correct program
var adjacent: [[Int]] = [[], [], []]
for (v, w) in [(0, 1), (1, 2)] {
adjacent[v].append(w)
adjacent[w].append(v)
}
print(adjacent)Lab 43: Graph implementations
Q0: What would Swift print?
What would Swift print?
var adjacent: [[Int]] = Array(repeating: [], count: 4)
for (v, w) in [(0, 1), (0, 2), (0, 3), (1, 2)] {
adjacent[v].append(w)
adjacent[w].append(v)
}
let degrees = adjacent.map(\.count)
print(degrees, degrees.reduce(0, +))Show answer and explanation
Answer[3, 2, 2, 1] 8
Each undirected edge adds one to the degree of both its ends, so the degrees add up to twice the number of edges: 2 × 4 = 8. This handshake rule is a quick check for any graph implementation.
Q1: A matrix graph
Write MatrixGraph, an adjacency matrix for an undirected graph, with addEdge,
hasEdge, and neighbors(of:), and a protocol Graph that both it and an
adjacency-list graph conform to. Then write one function, reachable(from:in:),
that works on any Graph, and check that both representations give the same
answer.
Show solution
protocol Graph {
var vertexCount: Int { get }
func neighbors(of v: Int) -> [Int]
}
struct ListGraph: Graph {
private var adjacent: [[Int]]
init(vertices: Int) { adjacent = Array(repeating: [], count: vertices) }
var vertexCount: Int { adjacent.count }
mutating func addEdge(_ v: Int, _ w: Int) { adjacent[v].append(w); adjacent[w].append(v) }
func neighbors(of v: Int) -> [Int] { adjacent[v] }
}
struct MatrixGraph: Graph {
private var matrix: [[Bool]]
init(vertices: Int) {
matrix = Array(repeating: Array(repeating: false, count: vertices), count: vertices)
}
var vertexCount: Int { matrix.count }
mutating func addEdge(_ v: Int, _ w: Int) { matrix[v][w] = true; matrix[w][v] = true }
func hasEdge(_ v: Int, _ w: Int) -> Bool { matrix[v][w] }
func neighbors(of v: Int) -> [Int] { matrix[v].indices.filter { matrix[v][$0] } }
}
func reachable(from s: Int, in graph: some Graph) -> Set<Int> {
var marked: Set = [s]
var stack = [s]
while let v = stack.popLast() {
for w in graph.neighbors(of: v) where marked.insert(w).inserted {
stack.append(w)
}
}
return marked
}
var list = ListGraph(vertices: 6)
var matrix = MatrixGraph(vertices: 6)
for (v, w) in [(0, 1), (1, 2), (3, 4)] {
list.addEdge(v, w)
matrix.addEdge(v, w)
}
assert(reachable(from: 0, in: list) == [0, 1, 2])
assert(reachable(from: 0, in: matrix) == reachable(from: 0, in: list))
assert(matrix.hasEdge(4, 3) && !matrix.hasEdge(0, 2))reachable does not know which representation it has. On the matrix, each
neighbors call scans a row, so the search is Θ(V²); on the lists, Θ(V + E).
Q2: Reversing a directed graph
Write reversed(_:) for a directed graph in adjacency lists, returning the graph
with every edge’s direction flipped, in Θ(V + E) time. Use it to find all vertices
that can reach a given vertex.
Show solution
func reversed(_ adjacent: [[Int]]) -> [[Int]] {
var result: [[Int]] = Array(repeating: [], count: adjacent.count)
for (v, neighbors) in adjacent.enumerated() {
for w in neighbors {
result[w].append(v)
}
}
return result
}
func reachable(from s: Int, _ adjacent: [[Int]]) -> Set<Int> {
var marked: Set = [s]
var stack = [s]
while let v = stack.popLast() {
for w in adjacent[v] where marked.insert(w).inserted {
stack.append(w)
}
}
return marked
}
let graph = [[1], [2], [], [2], [0]] // 0→1, 1→2, 3→2, 4→0
assert(reversed(graph) == [[4], [0], [1, 3], [], []])
assert(reachable(from: 2, reversed(graph)) == [2, 1, 3, 0, 4])Following edges backwards answers “who can reach 2?” with the same search that answers “where can 2 go?”. Project 9 uses the same trick in reverse: WordNet stores edges from a word’s meaning to more general meanings, and hyponyms, the more specific words, are found by following them the other way.
Q3: Word ladders
Two words are adjacent if they have the same length and differ in exactly one letter. Find the shortest ladder from one word to another through a word list, such as cold → cord → card → ward → warm, without building the graph first.
Show solution
func ladder(from start: String, to goal: String, words: Set<String>) -> [String]? {
var edgeTo: [String: String] = [:]
var seen: Set = [start]
var queue = [start]
var head = 0
let letters = "abcdefghijklmnopqrstuvwxyz"
while head < queue.count {
let word = queue[head]
head += 1
if word == goal {
var path = [goal]
while let previous = edgeTo[path.last!] { path.append(previous) }
return path.reversed()
}
var characters = Array(word)
for i in characters.indices {
let original = characters[i]
for letter in letters where letter != original {
characters[i] = letter
let neighbor = String(characters)
if words.contains(neighbor), seen.insert(neighbor).inserted {
edgeTo[neighbor] = word
queue.append(neighbor)
}
}
characters[i] = original
}
}
return nil
}
let words: Set = ["cold", "cord", "card", "ward", "warm", "word", "worm", "corm", "wore"]
assert(ladder(from: "cold", to: "warm", words: words)?.count == 5)
assert(ladder(from: "cold", to: "cold", words: words) == ["cold"])
assert(ladder(from: "cold", to: "wxyz", words: words) == nil)Each word’s neighbors are generated by trying every letter in every position, 25 × 4 candidates, each checked against the word set in constant time. The graph of all English words has no stored edges at all, yet BFS finds shortest ladders through it.
Q4 (optional): Counting self-loops and parallel edges
An edge list can contain self-loops (an edge from a vertex to itself) and parallel edges (the same pair twice). Write a function that counts each in an undirected edge list, in expected Θ(E) time.
Show solution
struct Pair: Hashable {
let low: Int
let high: Int
init(_ a: Int, _ b: Int) { (low, high) = (min(a, b), max(a, b)) }
}
func irregularities(_ edges: [(Int, Int)]) -> (selfLoops: Int, parallel: Int) {
var seen: Set<Pair> = []
var result = (selfLoops: 0, parallel: 0)
for (v, w) in edges {
if v == w { result.selfLoops += 1 }
if !seen.insert(Pair(v, w)).inserted { result.parallel += 1 }
}
return result
}
let edges = [(0, 1), (1, 0), (2, 2), (1, 2), (0, 1), (3, 3), (3, 3)]
let counts = irregularities(edges)
assert(counts.selfLoops == 3 && counts.parallel == 3)Normalizing each pair so the smaller vertex comes first makes (0, 1) and (1, 0) the same edge, which is what “undirected” means. Algorithms that assume simple graphs, such as Lesson 43’s cycle detection, can be protected by checks like this.
What’s next
Edges so far have all been equal. Next lesson: weighted edges, and the shortest paths that take them into account.