迷宮問題(記錄路徑)壓棧
阿新 • • 發佈:2018-12-12
上節課資料結構老師最後講的迷宮問題。老師用的方法其實就是深度優先搜尋。 這裡用廣度優先搜尋解決迷宮問題,順便溫習一下最近學的棧。 用佇列實現廣度優先搜尋。 用棧輸出路徑 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;
}