mirror of
https://github.com/multipleof4/lynchmark.git
synced 2026-01-14 16:47:55 +00:00
1 line
820 B
JavaScript
1 line
820 B
JavaScript
const findShortestPath = async (graph, startNode, endNode) => { const { default: PriorityQueue } = await import('https://cdn.jsdelivr.net/npm/js-priority-queue@0.1.5/priority-queue.min.js'); const distances = Object.keys(graph).reduce((acc, node) => (acc[node] = Infinity, acc), {}); const pq = new PriorityQueue({ comparator: (a, b) => a[1] - b[1] }); distances[startNode] = 0; pq.queue([startNode, 0]); while (pq.length) { const [currentNode, currentDist] = pq.dequeue(); if (currentDist > distances[currentNode]) continue; if (currentNode === endNode) return currentDist; for (const neighbor in graph[currentNode] || {}) { const newDist = currentDist + graph[currentNode][neighbor]; if (newDist < distances[neighbor]) { distances[neighbor] = newDist; pq.queue([neighbor, newDist]); } } } return distances[endNode]; }; |