您的位置:首页 > 编程语言

A星搜索(A* search, A Star search algorithm)算法实现代码

2010-10-13 20:26 741 查看
为了对A*算法的印象比较深刻一点,这几天抽了空参照前面转载的那篇介绍A*算法的文章实现了一个简易的A*算法,完全用纯C语言实现。代码贴在这里供以后参考。如果用来解决其他问题,可以移植过去,重新实现几个函数就行了,主要是扩展节点的函数。

注:如果想使用已有的比较好使的A*算法,推荐一个以前我使用过的C++写的A*程序,参见这里(http://code.google.com/p/a-star-algorithm-implementation/)。这个代码里有几个例子程序,可以参照一下,也有详细的readme,参照说明重新实现一下Node就行了。

/*
* file: test_astar.c
* author: MulinB@HUST
* date: 2010-10-10
* Test the A-star algorithm. Only for study.
*/
#include <stdio.h>
#include "astar_algorithm.h"

int map[M]
; //map for test
int main()
{
int i, j;
Node* node_list;
Node* p;
printf("Test A Star Algorithm! by MulinB@HUST, 2010-10-10/n");
//setup passable place
for (i=0; i<M; i++)
{
for (j=0; j<N; j++)
{
map[i][j] = AVAIL;
}
}
//setup obstacle
for (i=1; i<4; i++)
{
map[i][4] = UNAVAIL;
}
//setup start and end point
map[2][2] = START;
map[2][6] = END;

//print map
printf("-------------------map------------------/n");
for (i=0; i<M; i++)
{
for (j=0; j<N; j++)
{
printf("%3d  ", map[i][j]);
}
printf("/n");
}
printf("----------------------------------------/n");
//search
node_list = a_star_search(map, N, M, 2, 2, 2, 6);
if (node_list == NULL)
{
printf("No road found!/n");
}
else
{
printf("The cost of this road is %f/n", node_list->G);
printf("The road list is: /n");
p = node_list;
while (p)
{
printf("  (%d, %d)/n", p->i, p->j);
map[p->i][p->j] = ROAD;
p = p->parent; //track the road by the node->parent
}
//print result
printf("-------------------result---------------/n");
for (i=0; i<M; i++)
{
for (j=0; j<N; j++)
{
printf("%3d  ", map[i][j]);
}
printf("/n");
}
printf("----------------------------------------/n");
}

//clear the open and close list
destroy_openlist();
destroy_closelist();
return 0;
}


运行结果:

Test A Star Algorithm! by MulinB@HUST, 2010-10-10
-------------------map------------------
0 0 0 0 0 0 0 0
0 0 0 0 -1 0 0 0
0 0 100 0 -1 0 111 0
0 0 0 0 -1 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
----------------------------------------
The cost of this road is 68.000000
The road list is:
(2, 6)
(1, 6)
(0, 5)
(0, 4)
(0, 3)
(1, 2)
(2, 2)
-------------------result---------------
0 0 0 10 10 10 0 0
0 0 10 0 -1 0 10 0
0 0 10 0 -1 0 10 0
0 0 0 0 -1 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
----------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: