源代码:
#include <stdio.h>
#include <stdlib.h>
int maze[6+2][8+2] = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,1,1,1,0,1,1,1,1},
{1,1,0,1,0,1,0,1,0,1},
{1,0,1,0,0,1,1,1,1,1},
{1,0,1,1,1,0,0,1,1,1},
{1,1,0,0,1,1,0,0,0,1},
{1,0,1,1,0,0,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
typedef struct {
int i,j; //方块的位置
int pre; //记录前一步的位置
} Mark;
typedef struct {
Mark maze[60];
int rear, front; //队尾,队首指针
} Queue; //定义一个顺序队列
int path (int xb, int yb, int xe, int ye) {
Queue a;
int find = 0;
int i,j,k;
a.front = a.rear = -1; //初始化队列
a.rear++; //入队
a.maze[a.rear].i = xb;
a.maze[a.rear].j = yb;
a.maze[a.rear].pre = -1;
maze[xb][yb] = -1; //避免重复搜索
while (a.front!=a.rear && !find) {
a.front++;
i = a.maze[a.front].i;
j = a.maze[a.front].j; //出队
if (i==xe && j==ye) {
find = 1;
print(a,a.front);
return 1;
}
for (k=0; k<8; k++) {
switch (k) {
case 0:
i = a.maze[a.front].i - 1;
j = a.maze[a.front].j;
break;
case 1:
i = a.maze[a.front].i - 1;
j = a.maze[a.front].j + 1;
break;
case 2:
i = a.maze[a.front].i;
j = a.maze[a.front].j + 1;
break;
case 3:
i = a.maze[a.front].i + 1;
j = a.maze[a.front].j + 1;
break;
case 4:
i = a.maze[a.front].i + 1;
j = a.maze[a.front].j;
break;
case 5:
i = a.maze[a.front].i + 1;
j = a.maze[a.front].j - 1;
break;
case 6:
i = a.maze[a.front].i;
j = a.maze[a.front].j - 1;
break;
case 7:
i = a.maze[a.front].i - 1;
j = a.maze[a.front].j - 1;
break;
}
if (maze[i][j]==0) {
a.rear++; //将相邻的方块入队
a.maze[a.rear].i = i;
a.maze[a.rear].j = j;
a.maze[a.rear].pre = a.front;
maze[i][j] = -1;
}
}
}
return 0;
}
void print (Queue a, int front) {
int j,k;
k = front;
while (k != 0) { //倒序找最短路径
j = k;
k = a.maze[k].pre;
a.maze[j].pre = -1;
}
k = 0;
while (k<=front) {
if (a.maze[k].pre == -1) {
printf("(%d,%d) ", a.maze[k].i, a.maze[k].j);
}
k++;
}
return ;
}
int main() {
path(1, 1, 6, 8);
return 0;
}
运行结果: