Add Dijkstra.

This commit is contained in:
Oleksii Trekhleb 2018-05-03 06:47:09 +03:00
parent 8b057b10d0
commit ce7a4a930f
3 changed files with 51 additions and 9 deletions

View File

@ -33,10 +33,17 @@ export default function dijkstra(graph, startVertex) {
if (distanceToNeighborFromCurrent < existingDistanceToNeighbor) {
distances[neighbor.getKey()] = distanceToNeighborFromCurrent;
// Change priority.
if (queue.hasValue(neighbor)) {
queue.changePriority(neighbor, distances[neighbor.getKey()]);
}
}
// Add neighbor to the queue for further visiting.
queue.add(neighbor, distances[neighbor.getKey()]);
if (!queue.hasValue(neighbor)) {
queue.add(neighbor, distances[neighbor.getKey()]);
}
}
});

View File

@ -40,19 +40,28 @@ export default class PriorityQueue extends MinHeap {
* @return {PriorityQueue}
*/
changePriority(item, priority) {
const customFindingComparator = new Comparator((a, b) => {
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
});
this.remove(item, customFindingComparator);
this.remove(item, new Comparator(this.compareValue));
this.add(item, priority);
return this;
}
/**
* @param {*} item
* @return {Number[]}
*/
findByValue(item) {
return this.find(item, new Comparator(this.compareValue));
}
/**
* @param {*} item
* @return {boolean}
*/
hasValue(item) {
return this.findByValue(item).length > 0;
}
/**
* @param {*} a
* @param {*} b
@ -65,4 +74,17 @@ export default class PriorityQueue extends MinHeap {
return this.priorities[a] < this.priorities[b] ? -1 : 1;
}
/**
* @param {*} a
* @param {*} b
* @return {number}
*/
compareValue(a, b) {
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
}
}

View File

@ -87,4 +87,17 @@ describe('PriorityQueue', () => {
expect(priorityQueue.poll()).toBe(15);
expect(priorityQueue.poll()).toBe(10);
});
it('should be possible to search in priority queue by value', () => {
const priorityQueue = new PriorityQueue();
priorityQueue.add(10, 1);
priorityQueue.add(5, 2);
priorityQueue.add(100, 0);
priorityQueue.add(200, 0);
priorityQueue.add(15, 15);
expect(priorityQueue.hasValue(70)).toBeFalsy();
expect(priorityQueue.hasValue(15)).toBeTruthy();
});
});