迷宫问题(记录路径)压栈

迷宫问题(记录路径)压栈

上节课数据结构老师最后讲的迷宫问题。老师用的方法其实就是深度优先搜索。 这里用广度优先搜索解决迷宫问题,顺便温习一下最近学的栈。
用队列实现广度优先搜索。
用栈输出路径
迷宫问题(记录路径)压栈
using namespace std;
int maze[5][5],vis[5][5];
int bu[4][2]={1,0,-1,0,0,1,0,-1};
struct node{
int x;
int y;
int now;
int last;
node(int x=0,int y=0,int now=0,int last=0):x(x),y(y),now(now),last(last){};
}a[500];

迷宫问题(记录路径)压栈
bool check(int x,int y)
{
return x>=0&&x<5&&y>=0&&y<5&&vis[x][y]==0&&maze[x][y]==0;
}
int r=1;
void bfs(){
a[r].x=0;
a[r].y=0;
a[r].now=1;
a[r].last=0;
q.push(a[r]);

node p;
while(!q.empty()&&(p.x!=4||p.y!=4))
{
     p=q.front();
     q.pop();
    
        for(int i=0;i<=3;i++)
        {
            int nextx=p.x+bu[i][0];
            int nexty=p.y+bu[i][1];
            if(check(nextx,nexty)){
                vis[nextx][nexty]=1;
                r++;
                a[r].x=nextx;
                a[r].y=nexty;
                a[r].now=r;
                a[r].last=p.now;
                q.push(a[r]);
                
            }
    }
    
}
if(p.x==4&&p.y==4)
{
    
    while(p.last>0)
    {
        out.push(p);
        p=a[p.last];
    }
      cout<<"("<<0<<","<<" "<<0<<")"<<endl;
    while(!out.empty())
    {
        
        cout<<"("<<out.top().x<<","<<" "<<out.top().y<<")"<<endl;
        out.pop();
    }
    return;
}

}
int main(){

for(int i=0;i<=4;i++)
    for(int j=0;j<=4;j++)
        cin>>maze[i][j];
memset(vis, 0, sizeof(vis));
bfs();


return 0;

}