这道题在bfs求最短路的基础上,要求记录路径,观看了网上大佬的代码Orz,发现巧妙之处在于那个vis数组。
想记录下来主要是因为debug了好久QAQ...就是for循环中p值改变的问题。。详见注释吧。。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define ll long long
const int INF=0x3f3f3f3f;
int a[6][6];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int vis[6][6];
typedef pair<int,int> pp;
void bfs()
{
queue<pp>q;
memset(vis,-1,sizeof(vis));
pp p(0,0);
q.push(p);
vis[0][0]=0;
while(!q.empty())
{
p=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int xx=p.first+dx[i];
int yy=p.second+dy[i];
if(xx>=0&&xx<5&&yy>=0&&yy<5)
if(a[xx][yy]==0&&vis[xx][yy]==-1)
{
vis[xx][yy]=vis[p.first][p.second]+1;//巧妙之处,用vis记录路径
//p.first=xx;p.second=yy;//注:再循环时值已被改变了!!
q.push(make_pair(xx,yy));
}
}
//cout<<"q.size="<<q.size()<<endl;
if(vis[4][4]!=-1)
break;
}
/*for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
cout<<vis[i][j]<<" ";
cout<<endl;
}*/
pp a[30];
int tol=0;
p=make_pair(4,4);
a[tol++]=p;
while(true)
{
for(int i=0;i<4;i++)
{
int xx=p.first+dx[i];
int yy=p.second+dy[i];
if(xx>=0&&xx<5&&yy>=0&&yy<5)
if(vis[p.first][p.second]-vis[xx][yy]==1)
{
p.first=xx;p.second=yy;//此时可以改变,因为break了
a[tol++]=p;
break;
}
}
if(p.first==0&&p.second==0)
break;
}
//cout<<"tol="<<tol<<endl;
for(int i=tol-1;i>=0;i--)
printf("(%d, %d)\n",a[i].first,a[i].second);
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
scanf("%d",&a[i][j]);
bfs();
return 0;
}
后来重新刷了这道题,发现其实很简单。。多加一个pre数组记录路径,再用一个栈(或者n*n长的数组)逆序输出就好了。AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
typedef pair<int,int> pp;
#define mkp make_pair
int n=5;
int maze[7][7];
int d[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int vis[7][7]; //记录是否被访问,以及路径长度(步数)
pp pre[7][7];
stack<pp>ans; //也可以换成一个n*n的数组,逆序输出
void bfs()
{
pp st=mkp(0,0),en=mkp(4,4);
queue<pp>que;
memset(vis,0,sizeof(vis));
vis[st.first][st.second]=1;
pre[st.first][st.second]=mkp(-1,-1);
que.push(st);
while(!que.empty())
{
pp k=que.front();
que.pop();
if(k.first==en.first&&k.second==en.second) //到达终点
{
//printf("%d\n",vis[k.first][k.second]);
pp tmp=en;
ans.push(en);
while(tmp!=st) //把路径放入栈中,先进后出
{
tmp=pre[tmp.first][tmp.second];
ans.push(tmp);
}
break;
}
for(int i=0;i<4;i++)
{
int x=k.first+d[i][0],y=k.second+d[i][1];
if(x>=0&&x<n&&y>=0&&y<n&&maze[x][y]==0&&!vis[x][y])
{
vis[x][y]=vis[k.first][k.second]+1; //记录步数
pre[x][y]=mkp(k.first,k.second); //记录路径
que.push(mkp(x,y));
}
}
}
while(!ans.empty())
{
pp tmp=ans.top();
ans.pop();
printf("(%d, %d)\n",tmp.first,tmp.second);
}
}
int main()
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
scanf("%d",&maze[i][j]);
bfs();
return 0;
}