1. 程式人生 > >迷宮問題(BFS+路徑儲存) POJ-3984

迷宮問題(BFS+路徑儲存) POJ-3984

定義一個二維陣列: 

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實際上是指向了未知的一個區域,為什麼還是能通過,求解???