问题描述
function algorithm(){
if(startPoint === true && endPoint === true){
//add the heuristic distance to the start position from the final position
startPosition.h = distance([startPosition.x,startPosition.y]);
let openList = []
openList.push(startPosition)
let closedList = []
while (openList.length > 0){
//print(openList)
lowPos = 0;
for(let i = 0; i < openList.length; i++){
if(openList[i].f < openList[lowPos].f){
lowPos = i;
}
}
let currentPosition = openList[lowPos];
//currentPosition.check()
//if the currentPosition is the endPosition,retrace steps and find the path,then return this path
if(currentPosition === endPosition){
let curr = currentPosition;
let ret = [];
while(curr.parent != null){
curr.path()
ret.push(curr);
curr = curr.parent;
}
endPosition.end()
return ret.reverse();
}
openList.splice(lowPos,1);
closedList.push(currentPosition);
let neighbours = neighbors(currentPosition);
for(let i = 0; i < neighbours.length; i++){
let neighbour = neighbours[i];
if(closedList.includes(neighbour) || neighbour.colour == "black"){
continue;
}
neighbour.check()
let gscore = currentPosition.g + 1;
let gscoreBest = false;
if(openList.includes(neighbour) == false){
gscoreBest = true;
neighbour.h = distance([neighbour.x,neighbour.y]);
openList.push(neighbour);
}
else if(gscore < neighbour.g){
gscoreBest = true;
}
if(gscoreBest == true){
neighbour.parent = currentPosition;
neighbour.g = gscore;
neighbour.f = neighbour.g + neighbour.h;
}
}
}
}
//meaning that either the path is not possible or the final node/initial node
has not yet been placed.
return [];
}
这是我在 p5 中的星形算法,我正在尝试制作一个星形可视化项目,但由于某种原因,突出显示的块比预期的要多得多。 [
:https://i.stack.imgur.com/ILlOr.png 实际上它应该是这样的::https://i.stack.imgur.com/nsF5r.png第二张图片不是我的,它来自别人的实现:https://qiao.github.io/PathFinding.js/visual/ = 链接到第二张图片
我认为这与行的顺序有关:neighbor.check() 改变了块的颜色。
这是一个对角线解决方案,您可以看到由于某种原因左上角有紫色,这是我的问题。不应搜索左上角,但出于某种原因。
如果您需要我的更多代码,请告诉我。