【发布时间】:2015-01-11 15:34:46
【问题描述】:
我正在用 javascript 实现 A-Star 算法。它可以工作,但是在两个非常靠近的点之间创建路径需要很长时间:(1,1)到(6,6)需要几秒钟。我想知道我在算法中犯了哪些错误以及如何解决这些错误。
我的代码:
Node.prototype.genNeighbours = function() {
var right = new Node(this.x + 1, this.y);
var left = new Node(this.x - 1, this.y);
var top = new Node(this.x, this.y + 1);
var bottom = new Node(this.x, this.y - 1);
this.neighbours = [right, left, top, bottom];
}
AStar.prototype.getSmallestNode = function(openarr) {
var comp = 0;
for(var i = 0; i < openarr.length; i++) {
if(openarr[i].f < openarr[comp].f) comp = i
}
return comp;
}
AStar.prototype.calculateRoute = function(start, dest, arr){
var open = new Array();
var closed = new Array();
start.g = 0;
start.h = this.manhattanDistance(start.x, dest.x, start.y, dest.y);
start.f = start.h;
start.genNeighbours();
open.push(start);
while(open.length > 0) {
var currentNode = null;
this.getSmallestNode(open);
currentNode = open[0];
if(this.equals(currentNode,dest)) return currentNode;
currentNode.genNeighbours();
var iOfCurr = open.indexOf(currentNode);
open.splice(iOfCurr, 1);
closed.push(currentNode);
for(var i = 0; i < currentNode.neighbours.length; i++) {
var neighbour = currentNode.neighbours[i];
if(neighbour == null) continue;
var newG = currentNode.g + 1;
if(newG < neighbour.g) {
var iOfNeigh = open.indexOf(neighbour);
var iiOfNeigh = closed.indexOf(neighbour);
open.splice(iOfNeigh, 1);
closed.splice(iiOfNeigh,1);
}
if(open.indexOf(neighbour) == -1 && closed.indexOf(neighbour) == -1) {
neighbour.g = newG;
neighbour.h = this.manhattanDistance(neighbour.x, dest.x, neighbour.y, dest.y);
neighbour.f = neighbour.g + neighbour.h;
neighbour.parent = currentNode;
open.push(neighbour);
}
}
}
}
编辑:我现在已经解决了这个问题。这是因为我只是在调用: open.sort();它没有按节点的“f”值对节点进行排序。我写了一个自定义函数,现在算法运行得很快。
【问题讨论】:
-
什么是
genNeighbors()?您的优先队列在哪里? -
谢谢@Bergi。你让我意识到了问题所在。我没有对节点进行适当的排序。
-
这不是唯一的错误,我会写一个答案。
-
好的,谢谢。这是我第一次实现该算法,所以欢迎任何指针:)
-
欢迎您回答自己的问题,但您必须使用“回答您的问题”按钮才能将其作为答案归档并获得投票和接受。
标签: javascript a-star