我正在尝试使用Dijkstra的算法来寻找迷宫中每个位置的特定点。
我在这里找到了Dijkstra算法的JavaScript版本:
https://github.com/bm1362/dijkstra-js/blob/master/nodes.js
(谢谢bm1362!)
我接近创建迷宫图的方式如下:
// the maze
var maze =
[[1, 1, 1, 1],
[1, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 1, 1]];
maze2 = [];
var i = 0;
var mazeSize = 30;
for (var x = 0; x < maze[0].length; x++) {
for (var y = 0; y < maze[0].length; y++) {
if (maze[x][y] == 1) {
nodes.push(new node);
nodes[i].setPos((x) * (maze[0].length + 100), (y) * ((maze[0].length + 100)))
nodes[i].tmppos = [x, y];
nodes[i].id = i;
maze2[x + ',' + y] = nodes[i];
i++;
}
}
}
//sort nodes in order of x position
var sortedNodes = quickSort(nodes);
//var sortedNodes = nodes;
for (var i = 0; i < sortedNodes.length; i++) {
sortedNodes[i].number = i;
var n1 = sortedNodes[i];
var up = {}, down = {}, left = {}, right = {};
var pos = [];
up.x = n1.tmppos[0];
up.y = n1.tmppos[1] - 1;
pos.push(up);
down.x = n1.tmppos[0];
down.y = n1.tmppos[1] + 1;
pos.push(down);
left.x = n1.tmppos[0] - 1;
left.y = n1.tmppos[1];
pos.push(left);
right.x = n1.tmppos[0] + 1;
right.y = n1.tmppos[1];
pos.push(right);
for (var m = 0; m < pos.length; m++) {
if (maze[pos[m].x] != undefined && maze[pos[m].x][pos[m].y] != undefined && maze[pos[m].x][pos[m].y] == 1) {
var n2 = maze2[pos[m].x + ',' + pos[m].y];
var dist = calcDist(n1, n2);
sortedNodes[i].addConnection(n2);
connections.push({
a: n1,
b: n2,
dist: dist
})
}
}
}
我遇到的问题是即使所有节点似乎都有连接,但算法运行时,某些节点不会获得父集。但我尝试了很多不同的方法,但仍然无法让所有的父母都这样做。
我在这里创建了一个JS小提琴:http://jsfiddle.net/XcdCr/3/
非常感谢任何帮助。