首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用PHP创建A*搜索

使用PHP创建A*搜索
EN

Stack Overflow用户
提问于 2011-10-26 04:01:46
回答 1查看 593关注 0票数 16

我有一个存储为多维数组($map[row][col])的地图,我希望创建一条从A点到B点的路径。

由于我可以有一些转弯,弯道等障碍物,我希望使用A*搜索来计算最快的路径。

所以一般的函数是

f(x) = g(x) + h(x)

我拥有所有这些价值观。g(x)是移动的成本(保存在地图上);h(x)是A和B之间的线性距离。

所以我有了我需要的一切,但我有一个问题:我如何组织所有的东西?

我不需要测试替代路径,因为地图上的一个正方形可以通过,也可以不通过,所以当我到达目标时,它应该是最短的。

我如何组织所有的东西?

我试着使用多维数组,但是我迷路了。:(

编辑

我编写了一些代码,这是一堵很长的文字:)

代码语言:javascript
运行
复制
//$start = array(28, 19), $end = array(14, 19)
//$this->map->map is a multidimensional array, everything has a cost of 1, except for 
//blocking squares that cost 99
//$this->map->map == $this->radar
//blocking square at 23-17, 22-18, 22-19, 22-20, 23-21, 19-17, 20-18,20-19,20-20,19-21
//they are like 2 specular mustache :P
function createPath($start, $end)
{
    $found = false;
    $temp  = $this->cost($start, $end);

    foreach($temp as $t){
        if($t['cost'] == $this->map->map[$end[0]][$end[1]]) $found = true;
        $this->costStack[$t['cost']][] = array('grid' => $t['grid'], 'dir' => $t['dir']);
    }

    ksort($this->costStack);

    if(!$found) {
        foreach($this->costStack as $k => $stack){
            foreach($stack as $kn => $node){
                $curNode = $node['grid'];
                unset($this->costStack[$k][$kn]);
                break;
            }

            if(!count($this->costStack[$k])) unset($this->costStack[$k]);
            break;
        }
        $this->createPath($curNode, $end);
    }
}

function cost($current, $target)
{
    $return = array();

    //$AIM  = array('n' => array(-1,  0),'e' => array( 0,  1),'s' => array( 1,  0),'w' => array( 0, -1));
    foreach($this->AIM as $direction => $offset){
        $position[0] = $current[0] + $offset[0];
        $position[1] = $current[1] + $offset[1];

        //radar is a copy of the map
        if ( $this->radar[$position[0]][$position[1]] == 'V') continue;
        else $this->radar[$position[0]][$position[1]] =  'V';

        $h = (int) $this->distance($position, $target);
        $g = $this->map->map[$position[0]][$position[1]];

        $return[] = array('grid' => $position,
                          'dir'  => $direction,
                          'cost' => $h + $g);
    }

    return $return;
}

我希望你能理解所有的事情,我已经尽量说清楚了。

最终我可以到达我的目的地,只扩展更便宜的节点,但现在我有一个问题。

我怎样才能把它变成方向?我必须存储一堆顺序(即n、n、e等),如何识别这些值中的路径?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7895130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档