-
-
Save jdriselvato/5555b9394e8e136f92c1675122589a69 to your computer and use it in GitHub Desktop.
Graph data structure in Swift using an Adjacency Matrix.
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
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