实验四A星算法求解迷宫问题实验Word格式文档下载.docx
《实验四A星算法求解迷宫问题实验Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《实验四A星算法求解迷宫问题实验Word格式文档下载.docx(9页珍藏版)》请在冰豆网上搜索。
g(n)容易表示,即每走一步的代价是1,所以利用f(n)=g(n)+h(n)这种策略,我们可以不断地逼近目标点,从而找到问题的解。
时间复杂度:
m行n列的迷宫矩阵实现算法的时间复杂度为O(m*n).
实验结果:
实验源码:
#include<
queue>
vector>
iostream>
usingnamespacestd;
intdirec[4][2]={{0,1},{-1,0},{0,-1},{1,0}};
enumFlag
{
SEAL,
OPEN,
UNVISITED
};
typedefstructnode
int_x,_y;
//节点坐标(x,y)
int_G;
//实际已开销G
int_H;
//探测将开销H
int_F;
//优先级_F=_G+_H
structnode*pre;
//前驱顶点
}Queue_Node;
typedefstruct
Flagflag;
Queue_Node*point;
}Seal;
classA_Star
public:
//构造函数
A_Star()
{
input();
}
~A_Star()
for(inti=1;
i<
=_len;
++i)
{
for(intj=1;
j<
=_wid;
++j)
{
if(_seal[i][j].point!
=NULL)
{
delete_seal[i][j].point;
}
}
}
for(i=0;
delete[]_seal[i];
delete[]_maze[i];
delete[]_seal;
delete[]_maze;
voidinput()
cout<
<
"
输入:
迷宫左边长,上边宽!
例如:
3020"
endl;
cin>
>
_len>
_wid;
_seal=newSeal*[_len+1];
_maze=newunsignedchar*[_len+1];
for(inti=0;
_seal[i]=newSeal[_wid+1];
_maze[i]=newunsignedchar[_wid+1];
从下一行开始输入迷宫信息:
for(i=1;
cin>
_maze[i][j];
_seal[i][j].flag=UNVISITED;
_seal[i][j].point=NULL;
输入起点坐标,目标点坐标,例如:
113020"
_sx>
_sy>
_ex>
_ey;
if(_maze[_sx][_sy]=='
1'
||_maze[_ex][_ey]=='
||bound(_sx,_sy)==false||bound(_ex,_ey)==false)
cout<
不可能存在这样的情况!
return;
调用A*算法打印结果如下:
A();
//A*核心算法
voidA()
//源点放入开放列表
Queue_Node*p_node=newQueue_Node;
p_node->
pre=NULL;
_H=get_H(_sx,_sy);
_G=0;
_x=_sx;
_y=_sy;
_F=p_node->
_H+p_node->
_G;
_open.push(p_node);
_seal[_sx][_sy].flag=OPEN;
_seal[_sx][_sy].point=p_node;
while(!
_open.empty())
p_node=_open.top();
_open.pop();
intx=p_node->
_x;
inty=p_node->
_y;
_seal[x][y].flag=SEAL;
for(inti=0;
4;
inttx=x+direc[i][0];
intty=y+direc[i][1];
if(bound(tx,ty)==false||_maze[tx][ty]=='
||_seal[tx][ty].flag==SEAL)
continue;
if(_seal[tx][ty].flag==UNVISITED)
if(tx==_ex&
&
ty==_ey)
{
print(p_node);
cout<
("
tx<
"
ty<
)"
总共走了:
p_node->
_F<
步"
return;
}
Queue_Node*temp=newQueue_Node;
_seal[tx][ty].flag=OPEN;
_seal[tx][ty].point=temp;
temp->
pre=p_node;
_G=p_node->
_G+1;
_x=tx;
_y=ty;
_H=get_H(tx,ty);
_F=temp->
_G+temp->
_H;
_open.push(temp);
else
Queue_Node*temp=_seal[tx][ty].point;
if(p_node->
_G+1<
temp->
_G)
temp->
没有从("
_sx<
_sy<
)--->
_ex<
_ey<
)的路径"
//打印路径
voidprint(Queue_Node*p)
if(p==NULL)
print(p->
pre);
p->
_x<
_y<
),"
;
boolbound(intx,inty)
return(x<
=_len)&
(x>
=1)&
(y<
=_wid)&
(y>
=1);
intget_H(intx,inty)
returnab(x-_ex)+ab(y-_ey);
intab(inti)
returni<
0?
-i:
i;
private:
structcmp
booloperator()(Queue_Node*n1,Queue_Node*n2)
returnn1->
_F>
n2->
_F;
};
priority_queue<
Queue_Node*,vector<
Queue_Node*>
cmp>
_open;
//最小堆(开放列表)
int_len,_wid;
//迷宫左边长,上边宽
int_sx,_sy,_ex,_ey;
Seal**_seal;
//动态开辟封闭列表
unsignedchar**_maze;
//迷宫地图
intmain()
A_Startest;
return0;
}
三、实验目的
通过这次实验,使我对启发式搜索算法有了更进一步的理解,特别是估计函
数h(n)所起到的巨大重用。
一个好的估计函数对于启发式搜索算法来说是十分关键的。