-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.js
36 lines (23 loc) · 941 Bytes
/
dijkstra.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { sortNodesByDistance, getUnvisitedNeighbors, getAllNodes } from "./multiUseFunctions";
export default function dijkstra(grid, startNode, endNode) {
const visitedNodesInOrder = [];
startNode.distance = 0;
const unvisitedNodes = getAllNodes(grid);
while (unvisitedNodes.length) {
sortNodesByDistance(unvisitedNodes);
const current = unvisitedNodes.shift();
if (current.isWall) continue;
if (current.distance === Infinity) return visitedNodesInOrder;
current.isVisitedS = true;
visitedNodesInOrder.push(current);
if (current === endNode) return visitedNodesInOrder;
updateUnvisitedNeighbors(current, grid);
}
}
function updateUnvisitedNeighbors(node, grid) {
const unvisitedNeighbors = getUnvisitedNeighbors(node, grid, 'S');
for (const neighbor of unvisitedNeighbors) {
neighbor.distance = node.distance + neighbor.weight + 1;
neighbor.previousNode = node;
}
}