A*搜索算法以及其实现

来源:互联网 发布:网站流量统计java代码 编辑:程序博客网 时间:2024/06/05 20:45

初级知识(详见):http://www.policyalmanac.org/games/aStarTutorial.htm

如果英语不好的,可以看这个翻译版本的:http://www.52rd.com/Blog/Detail_RD.Blog_haochi_123_80.html

下面是一个自己写的一个模板:

/*
    author:gsw_叶残风
    date:2017.9.25
    algorithm: A* search test
*/
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
using namespace std;
class Node{
    public:
        int x,y;//坐标
        int f,h,g;
        //3个属性,g*(n)表示从起始点到达节点n的花费
        // h*(n)表示从当前状态n到目标状态的估计花费。
        bool operator < (const Node &a) const
        {
            return f>a.f;//最小值优先
        }
};
int mari[100][100];int n,m;
bool vis[100][100];int to[4][2]={0,1,0,-1,-1,0,1,0};
Node begin_node,end_node;
void init()
{
    memset(vis,0,sizeof(vis));
    memset(mari,0,sizeof(mari));
}
void search_A()
{
    priority_queue<Node>way;
    Node tem,nex;
    way.push(begin_node);
    while(!way.empty())
    {
        tem=way.top();
        way.pop();
        if(tem.x==end_node.x&&tem.y==end_node.y)
        {
            cout<<tem.f<<endl;
            return;
        }
        cout<<tem.x<<" "<<tem.y<<" "<<tem.g<<" "<<tem.h<<" "<<tem.f<<endl;
        vis[tem.x][tem.y]=1;
        for(int i=0;i<4;i++)
        {
            nex.x=tem.x+to[i][0];
            nex.y=tem.y+to[i][1];
            if(nex.x>=0&&nex.x<n&&nex.y>=0&&nex.y<m&&!vis[nex.x][nex.y]&&!mari[nex.x][nex.y])
            {
                nex.g=tem.g+1;
                nex.h=end_node.x-nex.x+end_node.y-nex.y;
                nex.f=nex.g+nex.h;
                way.push(nex);
            }
        }
    }
}
int main()
{
    cin>>n>>m;
    init();
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
            cin>>mari[i][j];
    cin>>begin_node.x>>begin_node.y>>end_node.x>>end_node.y;
    begin_node.g=0;begin_node.h=7;begin_node.f=7;
    cout<<"--------------"<<endl;
    search_A();
}
/*
5 4
0 0 0 0
0 1 0 0
0 1 0 0
0 1 1 1
0 0 0 0
0 0 4 3
*/

原创粉丝点击