Skip to content

Commit 1ab2f81

Browse files
committed
[KTLN-676] Add samples
1 parent 11011e6 commit 1ab2f81

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
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+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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(
12+
Pair(2, 10),
13+
Pair(3, 15)
14+
),
15+
2 to listOf(
16+
Pair(4, 12)
17+
),
18+
3 to listOf(
19+
Pair(4, 15)
20+
),
21+
4 to listOf(
22+
Pair(5, 12),
23+
Pair(6, 15)
24+
),
25+
5 to emptyList(),
26+
6 to emptyList()
27+
)
28+
29+
val shortestPaths = dijkstra(graph, 1)
30+
assertEquals(37, shortestPaths.getValue(6))
31+
}
32+
}

0 commit comments

Comments
 (0)