JavaScript - 改进我的网格搜索算法

时间:2015-10-25 20:49:58

标签: javascript algorithm search

我制作了自己的“GhettoSearch”,用于找到网格上2个给定坐标之间的最近路径,AKA是“坐标列表”。

网格是这样的数组:

var grid [ [somedata, [x,y,z], somedata], [somedata, [x,y,z], somedata] ]等。

我的开始和停止位置只是坐标,此时Z坐标无关紧要。

我几乎可以走到尽头,但由于我的成本函数,我做了一些事情。

搜索结果如下:http://i.imgur.com/2ZjQBrh.png

以下是我目前用于搜索的代码:

var Main = {
    GhettoSearch: function(Start, Stop, Grid){
    var Pgreed = 1; //From current position to next nearby nodes
    var Tgreed = 0.25; //from current position to target node

    var Pcost = 0;
    var Tcost = 0;

    var open = [];
    var closed = [];
    var aReturn = [];

    for (i = 0; i < Grid.length; i++) {
        Worldmap.GetNode("Node_" + Grid[i][0]).style.backgroundColor = "#FFFFFF";

        Pcost = Heuristics.Distance.Manhattan(Grid[i][1], Start, Pgreed);
        Tcost = Heuristics.Distance.Manhattan(Grid[i][1], Stop, Tgreed);

        open.push([i, (Pcost + Tcost)]);
    }

    do {
        var TmpData = [0, Infinity];
        var TmpForI = null;

        for (i = 0; i < open.length; i++) {
            if (open[i][1] < TmpData[1]) {
                TmpData[0] = open[i][0];
                TmpData[1] = open[i][1];
                TmpForI = i;
            }
        }

        closed.push(TmpData);
        open.splice(TmpForI, 1);

        for (i = 0; i < open.length; i++) {
            Start = Grid[TmpData[0]][1]; //is now the start for recently closed node

            Pcost = Heuristics.Distance.Manhattan(Grid[open[i][0]][1], Start, Pgreed);
            Tcost = Heuristics.Distance.Manhattan(Grid[open[i][0]][1], Stop, Tgreed);

            open[i] = [open[i][0], (Pcost + Tcost)];
        }

    } while (open.length > 0);

    var PathID = null;
    var TmpDist = Infinity;


    for (i = 0; i < closed.length; i++) {
        var NodeID = Grid[closed[i][0]][0];
        var NodeCoords = Grid[closed[i][0]][1];
        var NodeCost = closed[i][1];

        aReturn.push([NodeID, NodeCoords, NodeCost]);


        //var Dist = Heuristics.Distance.Manhattan(NodeCoords, Stop, 1);
        if (NodeCost < TmpDist) {
            TmpDist = NodeCost;
            PathID = i;//Because you will remove the closest cord elese. OR? will u xD
        }

    }

    aReturn.splice(PathID, closed.length);



    return aReturn;
    }
};

正如你在图像上看到的那样,当向上移动时,它会向后移动并填充直线路径以外的空白点,我该如何避免这种情况?

是的,我查看了不同的搜索方法,例如BFS和星号,但我在自己的搜索功能中实现这个问题

0 个答案:

没有答案