Skip to content

Instantly share code, notes, and snippets.

@jdriselvato
Forked from larryfox/adjacency-list.swift
Created March 6, 2022 04:21
Show Gist options
  • Save jdriselvato/e49f8d3007bc16fe7a8452a0d5280729 to your computer and use it in GitHub Desktop.
Save jdriselvato/e49f8d3007bc16fe7a8452a0d5280729 to your computer and use it in GitHub Desktop.
Adjacency list in Swift
// Found this lying around in my code folder from when I was
// first playing with Swift. Consider it public domain.
struct Graph<T: Hashable> {
let directed: Bool
var adj = Dictionary<T, [T]>()
init(directed d: Bool) {
directed = d
}
mutating func addVertex(v: T) {
self[v] = [T]()
}
mutating func addEdge(from v: T, to u: T) {
if self[v] == nil {
addVertex(v)
}
if self[u] == nil {
addVertex(u)
}
self[v]?.append(u)
if !directed {
self[u]?.append(v)
}
}
subscript(key: T) -> [T]? {
get {
return adj[key]
}
set(newValue) {
return adj[key] = newValue
}
}
}
// Example usage:
var graph = Graph<Int>(directed: true)
graph.addEdge(from: 1, to: 2)
graph.addEdge(from: 1, to: 3)
graph[1] // => [2,3]
graph.addVertex(4)
graph[4] // => []
graph.addEdge(from: 2, to: 4)
graph[2] // => [4]
graph[4] // => []
graph.addEdge(from: 3, to: 3)
graph[3] // => [3]
graph[8] // => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment