很基本的一道水题,以前看书对于定义的father的回溯用处不是很了解,这一次终于清楚它的用处了。
没有坑,但是之前对于回溯不了解,这一次也算是有收获了。
#include<cstdio>
#include<iostream>
using namespace std;
int a[6][6];
struct student
{
int x;
int y;
int father;
} stu[300];
void print(int num)
{
if(stu[num].x==0&&stu[num].y==0)
{
cout<<"(0, 0)"<<endl;
return ;
}
print(stu[num].father);
cout<<'('<<stu[num].x<<", "<<stu[num].y<<')'<<endl;
}
main()
{
int i,j,tx,ty;
int next[4][2]= {{0,1},{1,0},{0,-1},{-1,0}};
while(cin>>a[0][0])
{
cin>>a[0][1]>>a[0][2]>>a[0][3]>>a[0][4];
for(i=1; i<5; i++)
for(j=0; j<5; j++)
cin>>a[i][j];
int head=1,tail=1;
stu[tail].x=0;
stu[tail].y=0;
stu[tail].father=0;
tail++;
bool judge=false;
while(head<tail)
{
for(i=0; i<=3; i++)
{
tx=stu[head].x+next[i][0];
ty=stu[head].y+next[i][1];
if(tx>=0&&tx<5&&ty>=0&&ty<5&&a[tx][ty]==0)
{
stu[tail].x=tx;
stu[tail].y=ty;
stu[tail].father=head;
if(tx==4&&ty==4)
{
print(tail);
judge=true;
break;
}
tail++;
}
}
if(judge)break;
head++;
}
}
return 0;
}