#ifndef SEQQUEUE_H
#define SEQQUEUE_H
#include <stdio.h>
#include <stdlib.h>
typedef struct Point
{
int x;
int y;
struct Point* pre;
}Point;
typedef Point* DataType;
struct Node
{
DataType data;
struct Node* next;
};
typedef struct Node* PNode;
struct Queue
{
PNode first;
PNode tail;
};
typedef struct Queue* LinkQueue;
LinkQueue CreatQueue()
{
LinkQueue p;
p = (LinkQueue)malloc(sizeof(struct Queue));
if (p != NULL)
{
p->first = NULL;
p->tail = NULL;
}
else printf("wrong!\n");
return p;
}
int Empty(LinkQueue q)
{
return(q->first == NULL);
}
void Push(LinkQueue q, DataType x)
{
PNode p;
p = (PNode)malloc(sizeof(struct Node));
if (p == NULL) printf("wrong!\n");
else {
p->data = x;
p->next = NULL;
if (q->first == NULL)
{
q->first = p;
q->tail = p;
}
else
{
q->tail->next = p;
q->tail = p;
}
}
}
void Pop(LinkQueue q)
{
PNode p;
if (q->first == NULL)
printf("empty!\n");
else
{
p = q->first;
q->first = q->first->next;
free(p);
}
}
DataType Front(LinkQueue q)
{
if (q->first == NULL)
{
printf("empty!\n");
exit(-1);
}
else return (q->first->data);
}
#endif
#include <stdlib.h>
#include <stdio.h>
#include "Queue.h"
#include "Maze.h"
void PrintPath(Point* p, Maze* maze)
{
int mark[11][11] = { {0} };
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++)
{
mark[i][j] = maze->data[i][j];
}
}
while (p)
{
printf("(%d,%d) <- ", p->x, p->y);
mark[p->x][p->y] = '*';
p = p->pre;
}
printf("出发\n");
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++)
{
if (mark[i][j] == 1)
printf("%c ", 1);
else if (mark[i][j] == '*')
printf(" *");
else
printf(" ");
}
printf("\n");
}
}
void MazeBFS(int x1, int y1, int x2, int y2, Maze* maze)
{
int direction[8][2] = { {0,1}, {1,1}, {1,0}, {1,-1},{0,-1}, {-1,-1}, {-1,0}, {-1,1} };
LinkQueue queue = CreatQueue();
int** mark;
int n = maze->size;
int mov;
mark = (int**)malloc(sizeof(int*) * n);
for (int i = 0; i < maze->size; i++)
{
mark[i] = (int*)malloc(sizeof(int) * maze->size);
for (int j = 0; j < maze->size; j++)
mark[i][j] = maze->data[i][j];
}
Point* point = (Point*)malloc(sizeof(struct Point));
point->x = x1;
point->y = y1;
point->pre = NULL;
Push(queue, point);
int path_index = 0;
while (!Empty(queue))
{
Point* curPoint = Front(queue);
Pop(queue);
mark[curPoint->x][curPoint->y] = 2;
mov = 0;
while (mov < 8)
{
int nx = curPoint->x + direction[mov][0];
int ny = curPoint->y + direction[mov][1];
Point* nextPoint = (Point*)malloc(sizeof(struct Point));;
nextPoint->x = nx;
nextPoint->y = ny;
if (nx > 0 && nx < n-1 && ny > 0 && ny < n-1 && mark[nx][ny] == 0)
{
nextPoint->pre = curPoint;
mark[nx][ny] = 2;
if (nx == x2 && ny == y2)
{
printf("已到达,路径如下:\n");
PrintPath(nextPoint,maze);
}
Push(queue,nextPoint);
}
else mov++;
}
}
}
int main()
{
Maze* maze = InitMaze(9);
ReadFile(maze, "./maze.txt");
MazeBFS(1, 1, 9, 8, maze);
return 0;
}