Last active
March 6, 2022 04:21
-
-
Save davidinga/5c02eb8dfbfbdf201677903de518eb4b 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