Skip to content

Commit 1b29ea9

Browse files
authored
Merge pull request #872 from LeoColman/KTLN-676-dijkstra-algorithm
[KTLN-676] Add samples
2 parents 9ed815e + 32ae81b commit 1b29ea9

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.dijkstra
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class DijkstraUnitTest {
7+
8+
@Test
9+
fun `Should calculate shortest path when using Dijkstra algorithm`() {
10+
val graph = mapOf(
11+
1 to listOf(Pair(2, 10), Pair(3, 15)),
12+
2 to listOf(Pair(4, 12)),
13+
3 to listOf(Pair(4, 15)),
14+
4 to listOf(Pair(5, 12),Pair(6, 15)),
15+
5 to emptyList(),
16+
6 to emptyList()
17+
)
18+
19+
val shortestPaths = dijkstra(graph, 1)
20+
assertEquals(37, shortestPaths.getValue(6))
21+
}
22+
}

0 commit comments

Comments
 (0)