Skip to content

Instantly share code, notes, and snippets.

@jdriselvato
Forked from davidinga/GraphAM.swift
Created March 6, 2022 04:21
Show Gist options
  • Save jdriselvato/5555b9394e8e136f92c1675122589a69 to your computer and use it in GitHub Desktop.
Save jdriselvato/5555b9394e8e136f92c1675122589a69 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