-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathfindingAlgos.js
More file actions
91 lines (69 loc) · 1.95 KB
/
pathfindingAlgos.js
File metadata and controls
91 lines (69 loc) · 1.95 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
export function dijkstra(grid, startNode, finishNode){
if (startNode === finishNode){
return;
}
const visited = [];
startNode.distance = 0;
const nodes = getAllNodes(grid);
while (!!nodes.length){
sortByDist(nodes); // Should consider minheap/priority queue instead of array
const closest = nodes.shift();
if (closest.isWall){
continue;
}
if (closest.distance === Infinity){
return visited;
}
closest.isVisited = true;
visited.push(closest);
if (closest === finishNode){
return visited;
}
updateUnvisited(closest, grid);
}
}
function getUnvisitedAdjs(node, grid){
const neighbors = [];
const {col, row} = node;
if (row > 0){
neighbors.push(grid[row - 1][col]);
}
if (row < grid.length - 1){
neighbors.push(grid[row + 1][col]);
}
if (col > 0){
neighbors.push(grid[row][col - 1]);
}
if (col < grid[0].length - 1){
neighbors.push(grid[row][col + 1]);
}
return neighbors.filter(neighbor => !neighbor.isVisited);
}
function updateUnvisited(node, grid){
const unvisited = getUnvisitedAdjs(node, grid);
for (const neighbor of unvisited) {
neighbor.distance = node.distance + 1;
neighbor.previousNode = node;
}
}
function getAllNodes(grid) {
const nodes = [];
for (const row of grid) {
for (const node of row) {
nodes.push(node);
}
}
return nodes;
}
function sortByDist(nodes){
nodes.sort((node1, node2) => node1.distance - node2.distance);
}
export function getNodesInShortestPathOrder(finishNode) {
const nodesInShortestPathOrder = [];
let currentNode = finishNode;
while (currentNode.previousNode !== null) {
nodesInShortestPathOrder.unshift(currentNode);
currentNode = currentNode.previousNode;
}
return nodesInShortestPathOrder;
}