|
| 1 | +package com.baeldung.dijkstra |
| 2 | + |
| 3 | +import java.util.PriorityQueue |
| 4 | + |
| 5 | +fun dijkstra(graph: Map<Int, List<Pair<Int, Int>>>, start: Int): Map<Int, Int> { |
| 6 | + val distances = mutableMapOf<Int, Int>().withDefault { Int.MAX_VALUE } |
| 7 | + val priorityQueue = PriorityQueue<Pair<Int, Int>>(compareBy { it.second }).apply { |
| 8 | + add(start to 0) |
| 9 | + } |
| 10 | + distances[start] = 0 |
| 11 | + |
| 12 | + while (priorityQueue.isNotEmpty()) { |
| 13 | + val (node, currentDist) = priorityQueue.poll() |
| 14 | + graph[node]?.forEach { (adjacent, weight) -> |
| 15 | + val totalDist = currentDist + weight |
| 16 | + if (totalDist < distances.getValue(adjacent)) { |
| 17 | + distances[adjacent] = totalDist |
| 18 | + priorityQueue.add(adjacent to totalDist) |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + return distances |
| 23 | +} |
| 24 | + |
| 25 | +fun dijkstraWithLoops(graph: Map<Int, List<Pair<Int, Int>>>, start: Int): Map<Int, Int> { |
| 26 | + val distances = mutableMapOf<Int, Int>().withDefault { Int.MAX_VALUE } |
| 27 | + val priorityQueue = PriorityQueue<Pair<Int, Int>>(compareBy { it.second }) |
| 28 | + val visited = mutableSetOf<Pair<Int, Int>>() |
| 29 | + |
| 30 | + priorityQueue.add(start to 0) |
| 31 | + distances[start] = 0 |
| 32 | + |
| 33 | + while (priorityQueue.isNotEmpty()) { |
| 34 | + val (node, currentDist) = priorityQueue.poll() |
| 35 | + if (visited.add(node to currentDist)) { |
| 36 | + graph[node]?.forEach { (adjacent, weight) -> |
| 37 | + val totalDist = currentDist + weight |
| 38 | + if (totalDist < distances.getValue(adjacent)) { |
| 39 | + distances[adjacent] = totalDist |
| 40 | + priorityQueue.add(adjacent to totalDist) |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + return distances |
| 46 | +} |
0 commit comments