mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-07-08 02:14:56 +08:00
Add Dijkstra.
This commit is contained in:
@ -43,7 +43,7 @@ describe('dijkstra', () => {
|
|||||||
.addEdge(edgeFG)
|
.addEdge(edgeFG)
|
||||||
.addEdge(edgeEG);
|
.addEdge(edgeEG);
|
||||||
|
|
||||||
const distances = dijkstra(graph, vertexA);
|
const { distances, previousVertices } = dijkstra(graph, vertexA);
|
||||||
|
|
||||||
expect(distances).toEqual({
|
expect(distances).toEqual({
|
||||||
H: Infinity,
|
H: Infinity,
|
||||||
@ -55,5 +55,11 @@ describe('dijkstra', () => {
|
|||||||
G: 12,
|
G: 12,
|
||||||
F: 11,
|
F: 11,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(previousVertices.F.getKey()).toBe('D');
|
||||||
|
expect(previousVertices.D.getKey()).toBe('B');
|
||||||
|
expect(previousVertices.B.getKey()).toBe('A');
|
||||||
|
expect(previousVertices.G.getKey()).toBe('E');
|
||||||
|
expect(previousVertices.C.getKey()).toBe('A');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -7,6 +7,7 @@ import PriorityQueue from '../../../data-structures/priority-queue/PriorityQueue
|
|||||||
export default function dijkstra(graph, startVertex) {
|
export default function dijkstra(graph, startVertex) {
|
||||||
const distances = {};
|
const distances = {};
|
||||||
const visitedVertices = {};
|
const visitedVertices = {};
|
||||||
|
const previousVertices = {};
|
||||||
const queue = new PriorityQueue();
|
const queue = new PriorityQueue();
|
||||||
|
|
||||||
// Init all distances with infinity assuming that currently we can't reach
|
// Init all distances with infinity assuming that currently we can't reach
|
||||||
@ -38,6 +39,9 @@ export default function dijkstra(graph, startVertex) {
|
|||||||
if (queue.hasValue(neighbor)) {
|
if (queue.hasValue(neighbor)) {
|
||||||
queue.changePriority(neighbor, distances[neighbor.getKey()]);
|
queue.changePriority(neighbor, distances[neighbor.getKey()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Remember previous vertex.
|
||||||
|
previousVertices[neighbor.getKey()] = currentVertex;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add neighbor to the queue for further visiting.
|
// Add neighbor to the queue for further visiting.
|
||||||
@ -51,5 +55,8 @@ export default function dijkstra(graph, startVertex) {
|
|||||||
visitedVertices[currentVertex.getKey()] = currentVertex;
|
visitedVertices[currentVertex.getKey()] = currentVertex;
|
||||||
}
|
}
|
||||||
|
|
||||||
return distances;
|
return {
|
||||||
|
distances,
|
||||||
|
previousVertices,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user