Graphs
Build a Graph as an Adjacency List
Represent an undirected graph as a per-vertex list of neighbours. For every
edge (u, v), append v to adj[u] and u to adj[v]. Neighbour lists
keep insertion order so the graph is a stable, deterministic fixture for the
search lessons.
Algorithm
Basic Implementation
basic.swift
let edges = [[1, 2], [1, 3], [2, 4], [3, 4], [4, 5], [5, 6]]
var adj: [Int: [Int]] = [:]
for e in edges {
adj[e[0], default: []].append(e[1])
adj[e[1], default: []].append(e[0])
}
var parts: [String] = []
for v in adj.keys.sorted() {
let nbrs = adj[v]!.map { String($0) }.joined(separator: ", ")
parts.append("\(v): [\(nbrs)]")
}
print("{" + parts.joined(separator: ", ") + "}")
Complexity
- Build: O(V + E)
- Space: O(V + E)
Implementation notes
- Swift: a
[Int: [Int]]dictionary stores neighbours via subscript-with-default; keys are sorted before printing because dictionary order is unspecified. - The replay shows the adjacency list after each edge is added, matching the lesson spec.
adjacency list
Each edge adds two directed entries, one in each direction.