|
| 1 | + |
| 2 | + |
| 3 | +public struct GraphVertex<T> { |
| 4 | + public var data: T |
| 5 | + let uniqueID: Int |
| 6 | +} |
| 7 | + |
| 8 | +public struct Graph<T> { |
| 9 | + |
| 10 | + private var adjacencyMatrix: [[Int?]] = [] // row-major |
| 11 | + |
| 12 | + public init() { } // Silence default constructor |
| 13 | + |
| 14 | + public mutating func createVertex(data: T) -> GraphVertex<T> { |
| 15 | + let vertex = GraphVertex(data: data, uniqueID: adjacencyMatrix.count) |
| 16 | + |
| 17 | + // Expand each existing row to the right one column |
| 18 | + for i in 0..<adjacencyMatrix.count { |
| 19 | + adjacencyMatrix[i].append(nil) |
| 20 | + } |
| 21 | + |
| 22 | + // Add one new row at the bottom |
| 23 | + let newRow = [Int?](count: adjacencyMatrix.count + 1, repeatedValue: nil) |
| 24 | + adjacencyMatrix.append(newRow) |
| 25 | + |
| 26 | + return vertex |
| 27 | + } |
| 28 | + |
| 29 | + // Creates a directed edge source -----> dest. Represented by M[source][dest] = weight |
| 30 | + public mutating func connect(sourceVertex: GraphVertex<T>, toDestinationVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
| 31 | + adjacencyMatrix[sourceVertex.uniqueID][toDestinationVertex.uniqueID] = weight |
| 32 | + } |
| 33 | + |
| 34 | + // Creates an undirected edge by making 2 directed edges: some ----> other, and other ----> some |
| 35 | + public mutating func connect(someVertex: GraphVertex<T>, withVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
| 36 | + adjacencyMatrix[someVertex.uniqueID][withVertex.uniqueID] = weight |
| 37 | + adjacencyMatrix[withVertex.uniqueID][someVertex.uniqueID] = weight |
| 38 | + |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +var graph = Graph<Int>() |
| 46 | +let v1 = graph.createVertex(1) |
| 47 | +let v2 = graph.createVertex(2) |
| 48 | +let v3 = graph.createVertex(3) |
| 49 | +let v4 = graph.createVertex(4) |
| 50 | + |
| 51 | +// v1 ---> v2 ---> v3 ---> v4 |
| 52 | +// ^ | |
| 53 | +// | V |
| 54 | +// -----------<------------| |
| 55 | + |
| 56 | +graph.connect(v1, toDestinationVertex: v2) |
| 57 | +graph.connect(v2, toDestinationVertex: v3) |
| 58 | +graph.connect(v3, toDestinationVertex: v4) |
| 59 | +graph.connect(v4, toDestinationVertex: v1) |
0 commit comments