Skip to content

Commit ce7a4a9

Browse files
committedMay 3, 2018
Add Dijkstra.
1 parent 8b057b1 commit ce7a4a9

File tree

3 files changed

+51
-9
lines changed

3 files changed

+51
-9
lines changed
 

‎src/algorithms/graph/dijkstra/dijkstra.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,17 @@ export default function dijkstra(graph, startVertex) {
3333

3434
if (distanceToNeighborFromCurrent < existingDistanceToNeighbor) {
3535
distances[neighbor.getKey()] = distanceToNeighborFromCurrent;
36+
37+
// Change priority.
38+
if (queue.hasValue(neighbor)) {
39+
queue.changePriority(neighbor, distances[neighbor.getKey()]);
40+
}
3641
}
3742

3843
// Add neighbor to the queue for further visiting.
39-
queue.add(neighbor, distances[neighbor.getKey()]);
44+
if (!queue.hasValue(neighbor)) {
45+
queue.add(neighbor, distances[neighbor.getKey()]);
46+
}
4047
}
4148
});
4249

‎src/data-structures/priority-queue/PriorityQueue.js

+30-8
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,28 @@ export default class PriorityQueue extends MinHeap {
4040
* @return {PriorityQueue}
4141
*/
4242
changePriority(item, priority) {
43-
const customFindingComparator = new Comparator((a, b) => {
44-
if (a === b) {
45-
return 0;
46-
}
47-
return a < b ? -1 : 1;
48-
});
49-
50-
this.remove(item, customFindingComparator);
43+
this.remove(item, new Comparator(this.compareValue));
5144
this.add(item, priority);
5245

5346
return this;
5447
}
5548

49+
/**
50+
* @param {*} item
51+
* @return {Number[]}
52+
*/
53+
findByValue(item) {
54+
return this.find(item, new Comparator(this.compareValue));
55+
}
56+
57+
/**
58+
* @param {*} item
59+
* @return {boolean}
60+
*/
61+
hasValue(item) {
62+
return this.findByValue(item).length > 0;
63+
}
64+
5665
/**
5766
* @param {*} a
5867
* @param {*} b
@@ -65,4 +74,17 @@ export default class PriorityQueue extends MinHeap {
6574

6675
return this.priorities[a] < this.priorities[b] ? -1 : 1;
6776
}
77+
78+
/**
79+
* @param {*} a
80+
* @param {*} b
81+
* @return {number}
82+
*/
83+
compareValue(a, b) {
84+
if (a === b) {
85+
return 0;
86+
}
87+
88+
return a < b ? -1 : 1;
89+
}
6890
}

‎src/data-structures/priority-queue/__test__/PriorityQueue.test.js

+13
Original file line numberDiff line numberDiff line change
@@ -87,4 +87,17 @@ describe('PriorityQueue', () => {
8787
expect(priorityQueue.poll()).toBe(15);
8888
expect(priorityQueue.poll()).toBe(10);
8989
});
90+
91+
it('should be possible to search in priority queue by value', () => {
92+
const priorityQueue = new PriorityQueue();
93+
94+
priorityQueue.add(10, 1);
95+
priorityQueue.add(5, 2);
96+
priorityQueue.add(100, 0);
97+
priorityQueue.add(200, 0);
98+
priorityQueue.add(15, 15);
99+
100+
expect(priorityQueue.hasValue(70)).toBeFalsy();
101+
expect(priorityQueue.hasValue(15)).toBeTruthy();
102+
});
90103
});

0 commit comments

Comments
 (0)
Please sign in to comment.