-
Notifications
You must be signed in to change notification settings - Fork 0
/
dijkstra.ts
47 lines (41 loc) · 1.25 KB
/
dijkstra.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { priorityQueueMin } from "./priorityQueueMin"
import { priorityQueueMinHeap } from "./priorityQueueMinHeap"
const { log } = console
/**
* dijkstra
* @param getNeighbors
* @param getCostBetweenVertices
* @param source
* @param isTarget
*/
export function dijkstra<GVertex>(
getNeighbors: (v: GVertex) => GVertex[],
getCostBetweenVertices: (a: GVertex, b: GVertex) => number,
source: GVertex,
isTarget: (vertex: GVertex) => boolean,
queue = priorityQueueMinHeap<GVertex>()
): number {
let distances = { [`${source}`]: 0 }
queue.enqueue(source, 0)
let finalCost = 0
while (!queue.isEmpty()) {
const shortestVertex = queue.dequeue()
const currentVertex = shortestVertex.key
const neighborVertices = getNeighbors(currentVertex)
if (isTarget(currentVertex)) {
finalCost = shortestVertex.priority
break
}
for (const neighborVertex of neighborVertices) {
const newDistance = distances[`${currentVertex}`] + getCostBetweenVertices(
currentVertex,
neighborVertex
)
if (newDistance < (distances[`${neighborVertex}`] || Infinity)) {
distances[`${neighborVertex}`] = newDistance
queue.enqueue(neighborVertex, newDistance)
}
}
}
return finalCost
}