#include int Maze[5][5];
int map[5][5];
int dir[4][2] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
typedef struct Step {
int x, y;
int dis;
struct Step * pre;
}Step;
struct QNode_ {
Step *step;
struct QNode_ *next;
};
typedef struct QNode_ QNode;
struct Queue_
{
QNode * front; //队首
QNode * rear; //队尾
};
typedef struct Queue_ Queue;
Queue MyQueue;
void Qcreat(Queue * queue)
{
QNode * head;
head = (QNode*)malloc(sizeof(QNode));
queue->front = head;
queue->rear = head;
//queue->front->data = 0;
queue->front->next = NULL;
}
int QisEmpty(Queue * queue)
{
if (queue->front == queue->rear)
{
return 1;
}
else
{
return 0;
}
}
QNode * pop(Queue * queue)
{
if (QisEmpty(queue) != 1)
{
QNode *node;
node = queue->front->next;
queue->front->next = node->next;
if (node == queue->rear)
queue->rear = queue->front;
//queue->front->data = 0;
//free(node);
return node;
}
else
{
printf("队列为空\n");
}
}
void push(Queue * queue, QNode * node)
{
//QNode * node = (QNode*)malloc(sizeof(QNode));
queue->rear->next = node;
queue->rear = node;
//node->data = data;
node->next = NULL;
}
void QDestory(Queue * queue)
{
QNode * node;
while (queue->front != NULL)
{
node = queue->front;
queue->front = queue->front->next;
free(node);
}
}
int bfs(int x, int y)
{
int i;
QNode *s, *u, *v;
s = (QNode*)malloc(sizeof(QNode));
Step step_s;
s->step = &step_s;
s->step->pre = NULL;
s->step->x = x;
s->step->y = y;
s->step->dis = 0;
map[s->step->x][s->step->y] = 1;
push(&MyQueue, s);
while (!QisEmpty(&MyQueue))
{
u = pop(&MyQueue);
for (i = 0; i < 4; i++)
{
Step *step_v;
v = (QNode*)malloc(sizeof(QNode));
step_v = (Step*)malloc(sizeof(Step));
v->step = step_v;
if (u->step->x == 4 && u->step->y == 4)
{
return u->step->dis;
}
v->step->x = u->step->x + dir[i][0];
v->step->y = u->step->y + dir[i][1];
v->step->pre = u->step;
v->step->dis = u->step->dis + 1;
if (Maze[v->step->x][v->step->y] == 0 && map[v->step->x][v->step->y] == 0 &&
v->step->x >= 0 && v->step->x<5 && v->step->y >= 0 && v->step->y<5)
{
map[v->step->x][v->step->y] = 1;
push(&MyQueue, v);
}
}
}
return 0;
}
int main(void)
{
int i, j, distant;
int M,N;
Qcreat(&MyQueue);
scanf("%d" ,&M);
scanf("%d", &N);
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
scanf("%d", &Maze[i][j]);
}
}
distant = bfs(0, 0);
printf("%d", distant);
QDestory(&MyQueue);
return 0;
}