diff --git a/09_dijkstras_algorithm/kotlin/DijkstraAlgorithm.kt b/09_dijkstras_algorithm/kotlin/DijkstraAlgorithm.kt new file mode 100644 index 0000000..b17fde0 --- /dev/null +++ b/09_dijkstras_algorithm/kotlin/DijkstraAlgorithm.kt @@ -0,0 +1,77 @@ +// Граф +private val graph: MutableMap> = HashMap() + +// Список отслеживания обработанных узлов +private val processed: MutableList = ArrayList() + +fun main() { + graph["start"] = HashMap() + graph["start"]!!["a"] = 6.0 + graph["start"]!!["b"] = 2.0 + graph["a"] = HashMap() + graph["a"]!!["fin"] = 1.0 + graph["b"] = HashMap() + graph["b"]!!["a"] = 3.0 + graph["b"]!!["fin"] = 5.0 + graph["fin"] = HashMap() + + // Стоимость узлов + val costs: MutableMap = HashMap() + costs["a"] = 6.0 + costs["b"] = 2.0 + costs["fin"] = Double.POSITIVE_INFINITY + + // Таблица родителей + val parents: MutableMap = HashMap() + parents["a"] = "start" + parents["b"] = "start" + parents["fin"] = null + + + println("Cost from the start to each node:") + println(dijkstraAlgorithm(costs, parents)) +} + +fun dijkstraAlgorithm(costs: MutableMap, + parents: MutableMap): MutableMap { + + var node = findLowestCostNode(costs) + while (node != null) { + val cost = costs[node] + // Перебрать всех соседей текущего узла + val neighbors: Map = graph[node]!! + for (n in neighbors.keys) { + val newCost = cost!! + neighbors[n]!! + // Если к соседу можно быстрее добраться через текущий узел... + if (costs[n]!! > newCost) { + // ... обновить стоимость для этого узла + costs[n] = newCost + // Этот узел становится новым родителем для соседа + parents[n] = node + } + } + // Узел помечается как обработанный + processed.add(node) + + // Найти следующий узел для обработки и повторить цикл + node = findLowestCostNode(costs) + } + return costs // { a: 5, b: 2, fin: 6 } +} + +private fun findLowestCostNode(costs: Map): String? { + var lowestCost = Double.POSITIVE_INFINITY + var lowestCostNode: String? = null + + // Перебрать все узлы + for ((key, cost) in costs) { + // Если это узел с наименьшей стоимостью из уже виденных и + // он еще не был обработан... + if (cost < lowestCost && !processed.contains(key)) { + // ... он назначается новым узлом с наименьшей стоимостью + lowestCost = cost + lowestCostNode = key + } + } + return lowestCostNode +} \ No newline at end of file