回溯原来的节点用到两个栈:第一个栈用来将队列中的结点按照入队顺序压入栈,(0,0)节点首先被压入栈.
第二个栈用来记录路径,将第一个栈的栈顶元素依次[根据是不是路径上的节点]压入第二个栈,(0,0)此时在第二个栈的顶端
最后,将第二个栈里的元素依次弹出就是结果
#include<iostream>
#include<stack>//用来压入父节点
#include<queue>
using namespace std;
const int maxn=7;
int vis[maxn][maxn];
struct node
{
int num;//编号
int x;
int y;
int parent;
};
queue<node>que;
stack<node>s;
stack<node>s2;
int temp;
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}};
void bfs()
{
node cur;
node nex;
while(!que.empty())
{
cur=que.front();
s.push(cur);
que.pop();
for(int i=0; i<4; i++)
{
int xx=cur.x+dir[i][0];
int yy=cur.y+dir[i][1];
if(xx>=0&&xx<=4&&yy>=0&&yy<=4&&vis[xx][yy]!=1)
{
nex.x=xx;
nex.y=yy;
nex.parent=cur.num;
nex.num=temp;
temp++;
que.push(nex);
if(xx==4&&yy==4)
return;
}
}
}
}
int main()
{
for(int i=0; i<=4; i++)
for(int j=0; j<=4; j++)
cin>>vis[i][j];
node pp;
pp.x=0;
pp.y=0;
temp=0;
pp.num=temp;
temp++;
pp.parent=-1;
que.push(pp);
vis[pp.x][pp.y]=1;
bfs();
node qq;
while(!que.empty())
{
s.push(que.front());
que.pop();
}
qq=s.top();
s2.push(qq);
s.pop();
while(!s.empty())
{
pp=s.top();
s.pop();
if(qq.parent==pp.num)
{
s2.push(pp);
qq=pp;
}
}
while(!s2.empty())
{
pp=s2.top();
s2.pop();
cout<<"("<<pp.x<<", "<<pp.y<<")"<<endl;
}
return 0;
}