Skip to content

Commit cf6b035

Browse files
authored
Add Dijkstra's algorithm to Kotlin (egonSchiele#268)
1 parent 933acaf commit cf6b035

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// Граф
2+
private val graph: MutableMap<String, MutableMap<String, Double>> = HashMap()
3+
4+
// Список отслеживания обработанных узлов
5+
private val processed: MutableList<String> = ArrayList()
6+
7+
fun main() {
8+
graph["start"] = HashMap()
9+
graph["start"]!!["a"] = 6.0
10+
graph["start"]!!["b"] = 2.0
11+
graph["a"] = HashMap()
12+
graph["a"]!!["fin"] = 1.0
13+
graph["b"] = HashMap()
14+
graph["b"]!!["a"] = 3.0
15+
graph["b"]!!["fin"] = 5.0
16+
graph["fin"] = HashMap()
17+
18+
// Стоимость узлов
19+
val costs: MutableMap<String, Double> = HashMap()
20+
costs["a"] = 6.0
21+
costs["b"] = 2.0
22+
costs["fin"] = Double.POSITIVE_INFINITY
23+
24+
// Таблица родителей
25+
val parents: MutableMap<String, String?> = HashMap()
26+
parents["a"] = "start"
27+
parents["b"] = "start"
28+
parents["fin"] = null
29+
30+
31+
println("Cost from the start to each node:")
32+
println(dijkstraAlgorithm(costs, parents))
33+
}
34+
35+
fun dijkstraAlgorithm(costs: MutableMap<String, Double>,
36+
parents: MutableMap<String, String?>): MutableMap<String, Double> {
37+
38+
var node = findLowestCostNode(costs)
39+
while (node != null) {
40+
val cost = costs[node]
41+
// Перебрать всех соседей текущего узла
42+
val neighbors: Map<String, Double> = graph[node]!!
43+
for (n in neighbors.keys) {
44+
val newCost = cost!! + neighbors[n]!!
45+
// Если к соседу можно быстрее добраться через текущий узел...
46+
if (costs[n]!! > newCost) {
47+
// ... обновить стоимость для этого узла
48+
costs[n] = newCost
49+
// Этот узел становится новым родителем для соседа
50+
parents[n] = node
51+
}
52+
}
53+
// Узел помечается как обработанный
54+
processed.add(node)
55+
56+
// Найти следующий узел для обработки и повторить цикл
57+
node = findLowestCostNode(costs)
58+
}
59+
return costs // { a: 5, b: 2, fin: 6 }
60+
}
61+
62+
private fun findLowestCostNode(costs: Map<String, Double>): String? {
63+
var lowestCost = Double.POSITIVE_INFINITY
64+
var lowestCostNode: String? = null
65+
66+
// Перебрать все узлы
67+
for ((key, cost) in costs) {
68+
// Если это узел с наименьшей стоимостью из уже виденных и
69+
// он еще не был обработан...
70+
if (cost < lowestCost && !processed.contains(key)) {
71+
// ... он назначается новым узлом с наименьшей стоимостью
72+
lowestCost = cost
73+
lowestCostNode = key
74+
}
75+
}
76+
return lowestCostNode
77+
}

0 commit comments

Comments
 (0)