定义一个二维数组:
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)
亲测能过!
#include "iostream" #include "queue" #include "stack" using namespace std; struct point { int x,y; point *pre; point(int a,int b) { x=a; y=b; } point() { }//必须加这个,否则报错 }; int maze[5][5]; int vis[5][5]; point bfs() { point a[1000]; point start(0,0); start.pre=NULL; int count=0; queue<point> que; que.push(start); vis[0][0]=1; int next[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; while(!que.empty()) { count++; a[count]=que.front(); point cur = que.front(); que.pop(); if(cur.x==4&&cur.y==4) { return cur; } for(int i=0;i<=3;i++) { point tmp; tmp.x=cur.x+next[i][0]; tmp.y=cur.y+next[i][1]; if(tmp.x>=0&&tmp.y>=0&&tmp.x<=4&&tmp.y<=4&&maze[tmp.x][tmp.y]==0&&vis[tmp.x][tmp.y]==0) { vis[tmp.x][tmp.y]=1; tmp.pre=&a[count];//这两个的顺序可不要弄反了!!! que.push(tmp); } } } } void print(point cur) { stack<point> sta; while(cur.pre) { sta.push(cur); cur=*cur.pre; } cout<<'('<<0<<", "<<0<<')'<<endl; while(!sta.empty()) { point a=sta.top(); sta.pop(); cout<<'('<<a.x<<", "<<a.y<<')'<<endl; } } int main() { for(int i=0;i<=4;i++) { for(int j=0;j<=4;j++) cin>>maze[i][j]; } point a=bfs(); print(a); return 0; }
求解答?
上述代码中将cur指针返回,但是在bfs中point a是定义在子函数内的,出了函数数组就会释放,所以按道理print中的cur实际上是指向了未知的一个区域,为什么还是能通过,求解???