Hello, I’m having trouble getting this exercise right (totally stuck at this point):
Complete the missing if-statement body to handle any time a shorter distance from the vertex to the neighbor is discovered:
Consider how the distances and previous objects should be updated to account for the new shorter path.
Use the .add() method to add elements into the queue so you can evaluate the vertices with the shortest distances.
This is my solution:
const PriorityQueue = require(‘./PriorityQueue.js’);
const testGraph = require(‘./testGraph.js’);
const dijkstras = (graph, startingVertex) => {
const distances = {};
const previous = {};
const queue = new PriorityQueue();
queue.add({ vertex: startingVertex, priority: 0 });
graph.vertices.forEach((vertex) => {
distances[vertex.data] = Infinity;
previous[vertex.data] = null;
});
distances[startingVertex.data] = 0;
while (!queue.isEmpty()) {
const { vertex } = queue.popMin();
vertex.edges.forEach((edge) => {
const alternate = edge.weight + distances[vertex.data];
const neighborValue = edge.end.data;
if (alternate < distances[neighborValue]) {
distances[neighborValue] = alternate;
previous[neighborValue] = vertex.data;
queue.add({ vertex: edge.end, priority: alternate });
}
})
}
return { distances, previous };
};
const results = dijkstras(testGraph, testGraph.vertices[0]);
console.log(results);
module.exports = dijkstras;
I keep getting this error:
Make sure to pass in an object with a vertex and priority property to .add()
What I have tried:
This is the if statement I've tried. What am I missing?
if (alternate < distances[neighborValue]) {
distances[neighborValue] = alternate;
previous[neighborValue] = vertex.data;
queue.add({ vertex: edge.end, priority: alternate });
}