Last active
March 6, 2022 04:21
-
-
Save larryfox/f6325a69c7f8c7e6419d to your computer and use it in GitHub Desktop.
Adjacency list in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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