基于Astar算法的栅格地图最优路径搜索matlab仿真,可以修改任意数量栅格

1.算法描述

       Astar算法是一种图形搜索算法,常用于寻路。它是个以广度优先搜索为基础,Dijkstra算法与最佳优先(best fit)算法特点于一身的一种 算法。它通过下面这个函数来计算每个节点的优先级,然后选择优先级最高的节点作为下一个待遍历的节点。

 

       AStar(又称 A*),它结合了 Dijkstra 算法的节点信息(倾向于距离起点较近的节点)和贪心算法的最好优先搜索算法信息(倾向于距离目标较近的节点)。可以像 Dijkstra 算法一样保证找到最短路径,同时也像贪心最好优先搜索算法一样使用启发值对算法进行引导。简单点说,AStar的核心在于将游戏背景分为一个又一个格子,每个格子有自己的靠谱值,然后通过遍历起点的格子去找到周围靠谱的格子,接着继续遍历周围…… 最终找到终点。

 

实现步骤:

 

1.把起始格添加到开启列表。

 

2.重复如下的工作:

 

a) 寻找开启列表中估量代价F值最低的格子。我们称它为当前格。

 

b) 把它切换到关闭列表。

 

c) 对相邻的8格中的每一个进行如下操作

 

* 如果它不可通过或者已经在关闭列表中,略过它。反之如下。

 

* 如果它不在开启列表中,把它添加进去。把当前格作为这一格的父节点。记录这一格的F,G,H值。

 

* 如果它已经在开启列表中,用G值为参考检查新的路径是否更好。更低的G值意味着更好的路径。如果是这样,就把这一格的父节点改成当前格,并且重新计算这一格的GF值。如果你保持你的开启列表按F值排序,改变之后你可能需要重新对开启列表排序。

 

d) 停止,

 

* 把目标格添加进了关闭列表(注解),这时候路径被找到,或者

 

* 没有找到目标格,开启列表已经空了。这时候,路径不存在。

 

3.保存路径。从目标格开始,沿着每一格的父节点移动直到回到起始格。这就是你的路径。

 

2.仿真效果预览

matlab2022a仿真结果如下:

 

 

 

 

 

 

 

 

 

3.MATLAB核心程序

 

while ~max(ismember(setopen,goalposind))&&~isempty(setopen)
    [temp,ii]=min(setopencosts+setopenheuristics);
    [costs,heuristics,posinds]=findfvalue(setopen(ii),setopencosts(ii),field,goalposind);
    setclose=[setclose;setopen(ii)];setclosecosts=[setclosecosts;setopencosts(ii)];
    if ii>1&&ii<length(setopen)
        setopen=[setopen(1:ii-1);setopen(ii+1:end)];
        setopencosts=[setopencosts(1:ii-1);setopencosts(ii+1:end)];
        setopenheuristics=[setopenheuristics(1:ii-1);setopenheuristics(ii+1:end)];
        
    elseif 1==ii
        setopen=[setopen(ii+1:end)];
        setopencosts=[setopencosts(ii+1:end)];
        setopenheuristics=[setopenheuristics(ii+1:end)];
    else
        setopen=[setopen(ii+1:end)];
        setopencosts=[setopencosts(ii+1:end)];
        setopenheuristics=[setopenheuristics(ii+1:end)];
    end
    for jj=1:length(posinds)
        if ~isinf(costs(jj))
            if ~max([setopen;setclose]==posinds(jj))
                fieldpointers{posinds(jj)}=movementdirection(jj);
                 setopen = [setopen; posinds(jj)];
                 setopencosts = [setopencosts; costs(jj)];
                 setopenheuristics = [setopenheuristics; heuristics(jj)];
            elseif max(setopen==posinds(jj))
                i=find(setopen==posinds(jj));
                if setopencosts(i)>costs(jj)
                    setopencosts(i)=costs(jj);
                    setopenheuristics(i)=heuristics(jj);
                    fieldpointers{setopen(i)}=movementdirection(jj);
                    
                    
                end
            else i=find(setclose==posinds(jj));
                if setclosecosts(i)>costs(jj)
                   setclosecosts(i)=costs(jj);
                   fieldpointers{setclose(i)}=movementdirection(jj);  
                end
            end
        end
    end
    if isempty(setopen)
        break;
    end

 

  

 

posted @ 2023-03-18 21:57  我爱C编程  阅读(44)  评论(0编辑  收藏  举报