-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdijkstra.js
53 lines (50 loc) · 1.25 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function dijkstraSearch(maze, start, end) {
var nodeQueue = [];
var visitedRooms = [];
var roomCount = maze.getRoomCount();
for (var i = 0; i < roomCount; i++) {
visitedRooms.push(false);
}
// starting node
nodeQueue.push({
room:start,
fromEdge:null,
parent:null,
});
visitedRooms[start] = true;
while (nodeQueue.length > 0) {
var fromNode = nodeQueue.shift();
if (fromNode.room === end) {
// success
return reconstructPath(fromNode);
}
var vectors = maze.roomToVectors(fromNode.room).filter(function(vector) {
if (maze.edgeColors[vector.edge] !== Maze.OPEN) return false;
if (visitedRooms[vector.room]) return false;
return true;
});
for (var i = 0; i < vectors.length; i++) {
var neighborRoom = vectors[i].room;
nodeQueue.push({
room:neighborRoom,
fromEdge:vectors[i].edge,
parent:fromNode,
});
visitedRooms[neighborRoom] = true;
}
}
// impossible
return null;
function reconstructPath(node) {
var path = [];
while (node != null) {
path.push(node.room);
if (node.fromEdge != null) {
path.push(node.fromEdge);
}
node = node.parent;
}
path.reverse();
return path;
}
}