mirror of
https://github.com/multipleof4/lynchmark.git
synced 2026-01-14 16:47:55 +00:00
35 lines
944 B
JavaScript
35 lines
944 B
JavaScript
const findShortestPath = async (graph, start, end) => {
|
|
const { default: PriorityQueue } = await import(
|
|
'https://cdn.jsdelivr.net/npm/js-priority-queue@0.1.5/+esm'
|
|
);
|
|
|
|
const distances = Object.keys(graph).reduce((acc, node) => {
|
|
acc[node] = node === start ? 0 : Infinity;
|
|
return acc;
|
|
}, {});
|
|
|
|
const pq = new PriorityQueue({ comparator: (a, b) => a.dist - b.dist });
|
|
const visited = new Set();
|
|
|
|
pq.queue({ node: start, dist: 0 });
|
|
|
|
while (pq.length) {
|
|
const { node, dist } = pq.dequeue();
|
|
|
|
if (visited.has(node)) continue;
|
|
if (node === end) return dist;
|
|
|
|
visited.add(node);
|
|
|
|
for (const [neighbor, weight] of Object.entries(graph[node] || {})) {
|
|
const newDist = dist + weight;
|
|
if (newDist < distances[neighbor]) {
|
|
distances[neighbor] = newDist;
|
|
pq.queue({ node: neighbor, dist: newDist });
|
|
}
|
|
}
|
|
}
|
|
|
|
return distances[end];
|
|
};
|
|
export default findShortestPath; |