c 语言实现Astar算法
时间: 2023-02-28 14:10:52 浏览: 62
A*算法是一种广泛使用的路径规划算法,用于从起点到终点找到最短路径。下面是C语言实现A*算法的一个简单示例:
```
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#define ROW 10
#define COL 10
#define MAX 20
// 定义结构体表示格子信息
struct cell
{
int x, y;
int f, g, h;
};
// 判断某个格子是否在地图内
bool isValid(int x, int y)
{
return (x >= 0 && x < ROW && y >= 0 && y < COL);
}
// 判断某个格子是否是障碍
bool isUnBlocked(int grid[][COL], int x, int y)
{
if (grid[x][y] == 0)
return (true);
else
return (false);
}
// 判断某个格子是否已在开放列表或关闭列表中
bool isDestination(int x, int y, struct cell dest)
{
if (x == dest.x && y == dest.y)
return (true);
else
return (false);
}
// 计算曼哈顿距离
int manhattan(int x, int y, struct cell dest)
{
return abs(x - dest.x) + abs(y - dest.y);
}
// 存储路径
struct cell cameFrom[ROW][COL];
bool closedList[ROW][COL];
// A*算法实现
void aStarSearch(int grid[][COL], struct cell src, struct cell dest)
{
// 初始化
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
closedList[i][j] = false;
cameFrom[i][j].x = -1;
cameFrom[i][j].y = -1;
}
}
// 定义开放列表
struct cell openList[MAX];
int openListCount = 0;
openList[0] = src;
openListCount++;
src.f = 0;
src.g = 0;
src.h = 0;
while (openListCount