c语言编程拼多多,编程题4-迷宫寻路 (牛客网2018拼多多)

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值