Skip to content

Commit

Permalink
[KTLN-676] Add samples
Browse files Browse the repository at this point in the history
  • Loading branch information
LeoColman committed Apr 14, 2024
1 parent 1ab2f81 commit 3e04bd3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,27 @@ fun dijkstra(graph: Map<Int, List<Pair<Int, Int>>>, start: Int): Map<Int, Int> {
}
}
return distances
}
}

fun dijkstraWithLoops(graph: Map<Int, List<Pair<Int, Int>>>, start: Int): Map<Int, Int> {
val distances = mutableMapOf<Int, Int>().withDefault { Int.MAX_VALUE }
val priorityQueue = PriorityQueue<Pair<Int, Int>>(compareBy { it.second })
val visited = mutableSetOf<Pair<Int, Int>>()

priorityQueue.add(start to 0)
distances[start] = 0

while (priorityQueue.isNotEmpty()) {
val (node, currentDist) = priorityQueue.poll()
if (visited.add(node to currentDist)) {
graph[node]?.forEach { (adjacent, weight) ->
val totalDist = currentDist + weight
if (totalDist < distances.getValue(adjacent)) {
distances[adjacent] = totalDist
priorityQueue.add(adjacent to totalDist)
}
}
}
}
return distances
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,10 @@ class DijkstraUnitTest {
@Test
fun `Should calculate shortest path when using Dijkstra algorithm`() {
val graph = mapOf(
1 to listOf(
Pair(2, 10),
Pair(3, 15)
),
2 to listOf(
Pair(4, 12)
),
3 to listOf(
Pair(4, 15)
),
4 to listOf(
Pair(5, 12),
Pair(6, 15)
),
1 to listOf(Pair(2, 10), Pair(3, 15)),
2 to listOf(Pair(4, 12)),
3 to listOf(Pair(4, 15)),
4 to listOf(Pair(5, 12),Pair(6, 15)),
5 to emptyList(),
6 to emptyList()
)
Expand Down

0 comments on commit 3e04bd3

Please sign in to comment.