Skip to content

Commit 10154dc

Browse files
Add adjacency matrix implementation
1 parent 7d1fbb8 commit 10154dc

File tree

6 files changed

+69
-0
lines changed

6 files changed

+69
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>

0 commit comments

Comments
 (0)