Skip to content

Instantly share code, notes, and snippets.

@davidinga
Last active March 6, 2022 04:21
Show Gist options
  • Save davidinga/5c02eb8dfbfbdf201677903de518eb4b to your computer and use it in GitHub Desktop.
Save davidinga/5c02eb8dfbfbdf201677903de518eb4b to your computer and use it in GitHub Desktop.
Graph data structure in Swift using an Adjacency Matrix.
public struct GraphAM {
private var adjMatrix = [[Int?]]()
private var numberOfVertices: Int {
return adjMatrix.count
}
init(numberOfVertices: Int) {
adjMatrix = Array(repeating: Array(repeating: nil, count: numberOfVertices), count: numberOfVertices)
}
public mutating func addEdge(from source: Int, to destination: Int, with weight: Int? = nil) {
adjMatrix[source][destination] = weight ?? 1
}
public mutating func removeEdge(from source: Int, to destination: Int) {
if source < numberOfVertices && destination < numberOfVertices {
adjMatrix[source][destination] = nil
adjMatrix[destination][source] = nil
}
}
public func isEdge(from source: Int, to destination: Int) -> Bool {
return adjMatrix[source][destination] != nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment