题意:
迷宫找出口问题,要求输出最短路径
要点:
普通迷宫找出口问题我倒是会做,但这题要记录路径,所以抓瞎了。看了一下,主要是要用一个队列数组来实现队列,用front指向当前pop出的结点,用rear指向当前入队的结点,通过记录前驱来记录通过的路径,并且通过递归倒序输出数组也就是正序输出路径,注意起点是不包括的。
15303623 | Seasonal | 3984 | Accepted | 168K | 0MS | C++ | 944B | 2016-03-23 15:36:16 |
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int map[5][5];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
struct node
{
int x, y, pre;
}que[100];
void print(int i)//递归倒序输出经过的路径,头尾输出不了
{
if (que[i].pre != -1)
{
print(que[i].pre);
printf("(%d, %d)\n", que[i].x, que[i].y);
}
}
void bfs(int x1,int y1)
{
que[0].x = x1;
que[0].y = y1;
que[0].pre = -1;
int front = 0, rear = 1;//用队列数组
while (front < rear)
{
for (int i = 0; i < 4; i++)
{
int xx = dx[i] + que[front].x;
int yy = dy[i] + que[front].y;
if (xx < 0 || xx >= 5 || yy < 0 || yy >= 5 || map[xx][yy])
continue;
else
{
map[xx][yy] = 1;
que[rear].x = xx;
que[rear].y = yy;
que[rear].pre = front;//记录前驱,也就是路径
rear++; //入队
}
if (xx == 4 && yy == 4)
print(front);//用front尾部不包括,用rear-1尾部包括
}
front++; //出队
}
}
int main()
{
int i, j;
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
scanf("%d", &map[i][j]);
printf("(0, 0)\n");
bfs(0, 0);
printf("(4, 4)\n");
return 0;
}