A*算法的C语言实现:
#include<stdio.h>
#include<math.h>
#define MaxLength 100
#define Height 15
#define Width 20
#define Reachable 0
#define Bar 1
#define Pass 2
#define Source 3
#define Destination 4
#define Sequential 0
#define NoSolution 2
#define Infinity 0xfffffff
#define East (1 << 0)
#define South_East (1 << 1)
#define South (1 << 2)
#define South_West (1 << 3)
#define West (1 << 4)
#define North_West (1 << 5)
#define North (1 << 6)
#define North_East (1 << 7)
typedef struct
{
signed char x, y;
} Point;
const Point dir[8] =
{
{
0, 1},
{
1, 1},
{
1, 0},
{
1, -1},
{
0, -1},
{
-1, -1},
{
-1, 0},
{
-1, 1}
};
unsigned char within(int x, int y)
{
return (x >= 0 && y >= 0
&& x < Height && y < Width
);
typedef struct{
int x, y;
unsigned char reachable, sur, value;
} MapNode;
typedef struct Close{
MapNode *cur;
char vis;
struct Close *from;
float F, G;
int H;
}Close;
typedef struct
{
int length;
Close* Array[MaxLength];
}Open;
static MapNode graph[Height][Width];
static int srcX, srcY, dstX, dstY;
void initOpen(Open *q)
{
q->length = 0;
}
void push(Open *q, Close cls[Height][Width], int x, int y, float g)
{
Close *t;
int i, mintag;
cls[x][y].G = g;
cls[x][y].F = cls[x][y].G + cls[x][y].H;
q->Array[q->length++] = &(cls[x][y]);
mintag = q->length - 1;
for (i = 0; i < q->length - 1; i++)
{
if (q->Array[i]->F < q->Array[mintag]->F)
{
mintag = i;
}
}
t = q->Array[q->length - 1];
q->Array[q->length - 1] = q->Array[mintag];
q->Array[mintag] = t;
}
Close* shift(Open *q)
{
return q->Array[--q->length]
}
void initClose(Close cls[Height][Width], int sx, int sy, int dx, int dy)
{
int i, j;
for (i = 0; i < Height; i++)
{
for (j = 0; j < Width; j++)
{
cls[i][j].cur = &graph[i][j];
cls[i][j].vis = !graph[i][j].reachable;
cls[i][j].from = NULL;
cls[i][j].G = cls[i][j].F = 0;
cls[i][j].H = abs(dx - i) +<