思路:题意很简单,关键是用怎样的方式将路径保存下来,第一次接触这种需要输出路径的题,参考了别人的方法。在结构体中用一个变量来保存当前状态的上一个状态,采用模拟队列来实现出队和入队,用递归的方式来输出途径。
代码如下:
#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"
using namespace std;
int top,rear;
int maze[10][10];
int movex[4] = {1,-1,0,0}; //x前进方式
int movey[4] = {0,0,1,-1}; //y前进方式
struct node
{
int x,y,pre; //pre用来保存当前状态的前一个状态
}node[100];
bool is_block(int x,int y) //判断当前位置能不能走
{
if(x<0 || x>4 || y<0 || y>4)
{
return true;
}
if(maze[x][y])
{
return true;
}
return false;
}
void output(int i) //递归输出走过的坐标
{
if(node[i].pre != -1)
{
output(node[i].pre);
printf("(%d, %d)\n",node[i].x,node[i].y);
}
}
void bfs(int x,int y)
{
node[top].x = x;
node[top].y = y;
node[top].pre = -1;
while(top < rear) //队列不为空
{
for(int i = 0;i < 4;i++)
{
int xx = movex[i]+node[top].x;
int yy = movey[i]+node[top].y;
if(xx == 4 && yy == 4) //走到迷宫的右下角,输出路径
{
output(top);
}
if(is_block(xx,yy))
{
continue;
}
else
{
maze[xx][yy] = 1; //走过的地方变为1(墙壁),相当于标记为已走过
node[rear].x = xx;
node[rear].y = yy;
node[rear].pre = top;
rear++; //入队
}
}
top ++; //出队
}
}
int main()
{
while(~scanf("%d",&maze[0][0]))
{
for(int i = 1;i < 5;i++)
{
scanf("%d",&maze[0][i]);
}
for(int i = 1;i < 5;i++)
{
for(int j = 0;j < 5;j++)
{
scanf("%d",&maze[i][j]);
}
}
top = 0,rear = 1;
puts("(0, 0)");
bfs(0,0);
puts("(4, 4)");
}
return 0;
}