You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Dijkstra Algorithm/README.md
+138Lines changed: 138 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -132,6 +132,144 @@ From now we repeat all actions again and fill our table with new info!
132
132
| Path Length From Start | 0 | 3 | 8 | 1 | 2 |
133
133
| Path Vertices From Start |[A]|[A, B]|[A, B, C]|[A, D]|[A, D, E ]|
134
134
135
+
136
+
## Code implementation
137
+
First of all, lets create class, that will describe any Vertex in the graph.
138
+
It is pretty simple
139
+
```swift
140
+
openclassVertex {
141
+
142
+
//Every vertex should be unique, that's why we set up identifier
143
+
openvar identifier: String
144
+
145
+
//For dijkstra every vertex in the graph should be connected with at least one other vertex. But there can be some use cases,
146
+
//when you firstly initialize all vertices without neighbors. And then on next interation set up thei neighbors. So, initially neighbors is an empty array.
147
+
//Array contains tuples (Vertex, Double). Vertex is a neighbor and Double is as edge weight to that neighbor.
148
+
openvar neighbors: [(Vertex, Double)] = []
149
+
150
+
//As it was mentioned in algorithm description, default path length from start for all vertices should be as much as possible.
151
+
//It is var, because we will update it during algorithm execution.
152
+
openvar pathLengthFromStart =Double.infinity
153
+
154
+
//This array containt vertices, which we need to go through to reach this vertex from starting one
155
+
//As with path length from start, we will change this array during algorithm execution.
156
+
openvar pathVerticesFromStart: [Vertex] = []
157
+
158
+
publicinit(identifier: String) {
159
+
self.identifier= identifier
160
+
}
161
+
162
+
//This function let us use the same array of vertices again and again to calculate paths with different starting vertex.
163
+
//When we will need to set new starting vertex andd recalculate paths, then we will simply clear graph vertices' cashes.
164
+
openfuncclearCache() {
165
+
pathLengthFromStart =Double.infinity
166
+
pathVerticesFromStart = []
167
+
}
168
+
}
169
+
```
170
+
171
+
Because every vertex should be unique it is usefull to make them Hashable and according Equatable. We use identifier for this purposes.
0 commit comments