|
1 | 1 | public struct GraphEdge<T> {
|
2 |
| - let from: GraphVertex<T> |
3 |
| - let to: GraphVertex<T> |
4 |
| - let weight: Int |
| 2 | + let from: GraphVertex<T> |
| 3 | + let to: GraphVertex<T> |
| 4 | + let weight: Int |
5 | 5 | }
|
6 | 6 |
|
7 | 7 | public struct GraphVertex<T> {
|
8 |
| - public var data: T |
9 |
| - private var edges: [GraphEdge<T>] // This is a simple adjacency list, rather than matrix |
10 |
| - |
11 |
| - public mutating func connectTo(destinationVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
12 |
| - edges.append(GraphEdge(from: self, to: destinationVertex, weight: weight)) |
13 |
| - } |
14 |
| - |
15 |
| - public mutating func connectBetween(inout otherVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
16 |
| - edges.append(GraphEdge(from: self, to: otherVertex, weight: weight)) |
17 |
| - otherVertex.edges.append(GraphEdge(from: otherVertex, to: self, weight: weight)) |
18 |
| - } |
| 8 | + public var data: T |
| 9 | + private var edges: [GraphEdge<T>] = [] // This is a simple adjacency list, rather than matrix |
| 10 | + |
| 11 | + public init(data: T) { |
| 12 | + self.data = data |
| 13 | + } |
| 14 | + |
| 15 | + // Creates a directed edge self -----> dest |
| 16 | + public mutating func connectTo(destinationVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
| 17 | + edges.append(GraphEdge(from: self, to: destinationVertex, weight: weight)) |
| 18 | + } |
| 19 | + |
| 20 | + // Creates an undirected edge by making 2 directed edges: self ----> other, and other ----> self |
| 21 | + public mutating func connectBetween(inout otherVertex: GraphVertex<T>, withWeight weight: Int = 0) { |
| 22 | + edges.append(GraphEdge(from: self, to: otherVertex, weight: weight)) |
| 23 | + otherVertex.edges.append(GraphEdge(from: otherVertex, to: self, weight: weight)) |
| 24 | + } |
19 | 25 | }
|
20 | 26 |
|
21 | 27 |
|
| 28 | + |
| 29 | + |
| 30 | +var v1 = GraphVertex(data: 1) |
| 31 | +var v2 = GraphVertex(data: 2) |
| 32 | +var v3 = GraphVertex(data: 3) |
| 33 | +var v4 = GraphVertex(data: 4) |
| 34 | + |
| 35 | +// v1 ---> v2 ---> v3 ---> v4 |
| 36 | +// ^ | |
| 37 | +// | V |
| 38 | +// -----------<------------| |
| 39 | +v1.connectTo(v2) |
| 40 | +v2.connectTo(v3) |
| 41 | +v3.connectTo(v4) |
| 42 | +v4.connectTo(v1) |
0 commit comments