@@ -77,6 +77,46 @@ object Graphs {
7777 }
7878 }
7979
80+ /* *
81+ * Implementation of Dijkstra's Algorithm
82+ * @param start the starting vertex
83+ * @param vertices the set of all vertices
84+ * @param neighbors a function that returns the neighbors of a vertex
85+ * @param weight a function that returns the weight of an edge
86+ * @return the shortest paths from the start vertex to all other vertices
87+ */
88+ fun <V > shortestPaths (
89+ start : V ,
90+ neighbors : (V ) -> List <V >,
91+ weight : (V , V ) -> Double = { _, _ -> 1.0 }
92+ ): ShortestPaths <V > {
93+ val pred = mutableMapOf<V , V >()
94+ val dist = mutableMapOf<V , Double >()
95+ val visited = mutableSetOf<V >()
96+ dist[start] = 0.0
97+ val queue = PriorityQueue { l: V , r: V ->
98+ compareDoubles(
99+ dist.getOrDefault(l, Double .MAX_VALUE ),
100+ dist.getOrDefault(r, Double .MAX_VALUE )
101+ )
102+ }
103+ queue.add(start)
104+ while (queue.isNotEmpty()) {
105+ val vertex = queue.poll()
106+ visited.add(vertex)
107+ val distanceToVertex = dist.getOrDefault(vertex, Double .MAX_VALUE )
108+ neighbors(vertex).filter { it !in visited }.forEach { neighbor ->
109+ val distanceThroughVertex = distanceToVertex + weight(vertex, neighbor)
110+ if (distanceThroughVertex < dist.getOrDefault(neighbor, Double .MAX_VALUE )) {
111+ pred[neighbor] = vertex
112+ dist[neighbor] = distanceThroughVertex
113+ queue.add(neighbor)
114+ }
115+ }
116+ }
117+ return ShortestPaths (start, dist, pred)
118+ }
119+
80120 /* *
81121 * Implementation of Dijkstra's Algorithm
82122 * @param start the starting vertex
0 commit comments