每当我走向某个方向(没有对角线)时,我会发现周围有5x5的区域。我发现" G",我必须找到通往起点的最短路径。
所以我正在为两种情况尝试BFS。它似乎适用于一个方向的简单路径,如:
????####
????..S#
????####
????????
????????
地图如下所示:
########
#.....S#
#.######
#......#
########
但是当我有很多可能性时,它有时会被卡住。它发现"最接近" (不太确定)"?"符号,返回路径,我再次从这一点转到第一个坐标和BFS。但是当我走向那个方向时,我有时会陷入困境,BFS和算法会发现更接近" ""在相反的方向,然后我来回走。
我认为我的算法有问题,因为路径返回例如左/右与3-4个节点不同。
function BFS(position,map,checked,target,avoid){
var Q = [[new Node(position.x,position.y)]];
var Path;
d=0;
while(Q.length >0){
Path = Q.shift();
vertex = Path[Path.length-1];
if(Map[vertex.y][vertex.x] == target){
return Path;
}
else if(checked[vertex.y][vertex.x] == 0){
if(vertex.x+1<C && Map[vertex.y][vertex.x+1] !="#" && checked[vertex.y][vertex.x+1] == 0){
new_path = Path.slice();
new_path.push(new Node(vertex.x+1,vertex.y));
Q.unshift(new_path);
}
if(vertex.x+1<C && Map[vertex.y][vertex.x+1] == "G"){
G_discovered = true;
G_position = new Node(vertex.x+1, vertex.y);
}
if(vertex.y+1<R && Map[vertex.y+1][vertex.x] !="#" && checked[vertex.y+1][vertex.x] == 0){
new_path = Path.slice();
new_path.push(new Node(vertex.x,vertex.y+1));
Q.unshift(new_path);
}
if(vertex.y+1<R && Map[vertex.y+1][vertex.x] == "G"){
G_discovered = true;
G_position = new Node(vertex.x, vertex.y+1);
}
if(vertex.x-1>=0 && Map[vertex.y][vertex.x-1] !="#" && checked[vertex.y][vertex.x-1] == 0){
new_path = Path.slice();
new_path.push(new Node(vertex.x-1,vertex.y));
Q.unshift(new_path);
}
if(vertex.x-1>=0 && Map[vertex.y][vertex.x-1] == "G" ){
G_discovered = true;
G_position = new Node(vertex.x-1, vertex.y);
}
if(vertex.y-1>=0 && Map[vertex.y-1][vertex.x] !="#" && checked[vertex.y-1][vertex.x] == 0){
new_path = Path.slice();
new_path.push(new Node(vertex.x,vertex.y-1));
Q.unshift(new_path);
}
if(vertex.y-1>=0 && Map[vertex.y-1][vertex.x] == "G"){
G_discovered = true;
G_position = new Node(vertex.x, vertex.y-1);
}
d++;
checked[vertex.y][vertex.x] = 1;
}
}
return "no path found"
}
我在Map对象中读取的每一个动作都会清除已检查的数组