在我浏览参考了大多数最短路径迷宫后,决定写一篇随机迷宫和所有路径的代码。
话不多说,直接上代码。
#include <stdio.h>
#include<time.h>
#include <stdlib.h>
#define SIZE 1024
struct Box //表示一个格子的位置信息
{
int x; //横坐标
int y; //纵坐标
int pre; //前一个格子再在队列里面存放的位置(下标)
};
typedef struct Box Box;
//顺序队列存放路径的信息
struct Queue
{
Box data[SIZE];
int front;
int rear;
};
typedef struct Queue Queue;
//初始化顺序队列
int InitQueue(Queue* q)
{
q->front = q->rear = -1;
return 1;
}
//进队操作
int push(Queue* q, Box b)
{
if (q->rear == SIZE - 1)
{
return 0;
}
(q->rear)++;
q->data[q->rear] = b;
return 1;
}
//判断队列是否为空
int EmptyQueue(Queue* q)
{
return (q->front == q->rear) ? 1 : 0;
}
//出队操作(只是操作对头指针,元素实际还保留在队列中)
int pop(Queue* q, Box* b)
{
if (q->front == q->rear)
{
return 0;
}
(q->front)++;
*b = q->data[q->front];
return 1;
}
//打印路径
void ShowPath(Queue* q, int front)
{
int i=front;
printf("迷宫路径(逆序):\n");
while (front != 0)
{
printf("(%d,%d)->",q->data[i].x,q->data[i].y);
i = q->data[front].pre;
front = q->data[front].pre;
}
printf("(1,1)");
printf("\n");
}
int Walk(Queue* q, int x1, int y1, int x2, int y2,int map[100][100])
{
Box now;
int i, j, i0, j0;
now.x = x1;
now.y = y1;
now.pre = -1;
push(q, now); //入口信息入队
map[x1][y1] = -1;
while (EmptyQueue(q) != 1)
{
pop(q, &now);
i = now.x;
j = now.y;
int dir;
for (dir = 0; dir < 4; dir++) //循环四次,遍历四个方向 上 右 下 左
{
switch (dir)
{
case 0: //方向上
i0 = i - 1;
j0 = j;
break;
case 1: //方向又
i0 = i;
j0 = j + 1;
break;
case 2: //方向下
i0 = i + 1;
j0 = j;
break;
case 3: //方向左
i0 = i;
j0 = j - 1;
break;
}
//判断该点是否可走
if (i0 >= 1 && j0 >= 1 && i0 <= x2 && j0 <= y2 && map[i0][j0] == 0) //格子可以走
{
now.x = i0;
now.y = j0;
now.pre = q->front;
push(q, now);
map[i0][j0] = -1; //该点已经走过
}
}map[x2][y2] = 0;
}
int n = 0;
for (int k = 0;k <=q->rear;k++)
{
if (q->data[k].x == x2 && q->data[k].y == y2)
{
ShowPath(q, k);
n++;
}
}
return n;
}
int main()
{
Queue queue;
int a = 0;
printf("随机迷宫请按0,自定迷宫请按1\n");
scanf_s("%d", &a);
InitQueue(&queue);
printf("输入迷宫出口\n");
int m = 0, n = 0; int M[100][100] = { 1 };
scanf_s("%d %d", &m, &n);
switch (a)
{
case 0:
srand((unsigned)time(NULL));
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
{
int random_number = rand() % 2;
M[i][j] = random_number;
}
M[1][1] = 0;
M[m][n] = 0;
break;
case 1:
printf("请输入迷宫图");
for (int i = 1;i <= n;i++)
for (int j = 1;j <= m;j++)
{
int b = 0;
scanf_s("%d", &b);
M[i][j] = b;
}
break;
}
for (int i = 1;i <= n;i++)
{
for (int j = 1;j <= m;j++)
{
printf("%d ", M[i][j]);
}
printf("\n");
}
if (Walk(&queue, 1, 1, m, n,M) == 0)
{
printf("路径不存在\n");
}
return 0;
}