迷宫问题
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
经典BFS题目,主要注意记录路径的保存。用并查集再加上栈就行。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<stack> #include<stdlib.h> #include<map> #include<vector> #include<queue> #include<set> #include<ctype.h> #define zuida 100000 using namespace std; struct node { int x,y; }dis[6][6]; int abc[6][6]; int vis[6][6]; stack <node> p; void sta(int i,int j) { if(i==0&&j==0) { cout<<"(0, 0)"<<endl; return ; } else { node t; t.x=i; t.y=j; p.push(t); sta(dis[i][j].x,dis[i][j].y); } } void bfs() { queue<node> Q; node a,b,c; a.x=0; a.y=0; int dx[]={0,0,-1,1}; int dy[]={1,-1,0,0}; Q.push(a); dis[0][0].x=0; dis[0][0].y=0; while(!Q.empty()) { b=Q.front(); Q.pop(); int i,j;int xx,yy; for(i=0;i<4;i++) { xx=dx[i]+b.x; yy=dy[i]+b.y; if(xx==4&&yy==4) { sta(b.x,b.y); return ; } if(xx>=0&&xx<=5&&yy>=0&&yy<=5&&abc[xx][yy]==0&&vis[xx][yy]==0) { dis[xx][yy].x=b.x; dis[xx][yy].y=b.y; c.x=xx; c.y=yy; Q.push(c); abc[xx][yy]=1; } } } } int main() { memset(vis,0,sizeof(vis)); int i,j; for(i=0;i<5;i++) for(j=0;j<5;j++) cin>>abc[i][j]; bfs(); while(!p.empty()) { cout<<'('<<p.top().x<<", "<<p.top().y<<')'<<endl; p.pop(); } cout<<"(4, 4)"<<endl; return 0; }