題目可以說是很經典的一道打印迷宮路徑問題了,具體的思路就是定義結構體,裏面存當前的位置和當前位置的前一個位置,等找到終點之後再把路徑上的每一個點輸出就好了,具體的代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int mp[5][5],vis[5][5];
int mv[4][2] = {0,1,0,-1,-1,0,1,0};
struct node
{
int x,y,pre;
};
node que[1010];
void print(int last)
{
if(que[last].pre != -1)
{
print(que[last].pre);
printf("(%d, %d)\n",que[last].x,que[last].y);
}
}
void bfs()
{
int frt = 0,rear = 0;
que[rear].x = 0;
que[rear].y = 0;
que[rear++].pre = -1;
vis[0][0] = 1;
while(frt != rear)
{
int next_x,next_y;
for(int i = 0;i < 4; i++)
{
next_x = que[frt].x + mv[i][0];
next_y = que[frt].y + mv[i][1];
if(next_x >= 0 && next_y >= 0 && next_x < 5 && next_y < 5 && !vis[next_x][next_y] && mp[next_x][next_y] == 0)
{
que[rear].x = next_x;
que[rear].y = next_y;
que[rear].pre = frt;
vis[next_x][next_y] = 1;
rear++;
}
if(next_x == 4 && next_y == 4)
{
print(rear - 1);
}
}
frt++;
}
}
int main()
{
for(int i = 0;i < 5; i++)
for(int j = 0;j < 5; j++)
scanf("%d",&mp[i][j]);
printf("(0, 0)\n");
bfs();
return 0;
}