BFS

POJ3984 迷宮

定義一個二維數組: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表示可以走的路,只能橫着走或豎着

走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。

我的代碼:

#include <iostream>
#include <queue>
using namespace std; 

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};
struct step
{
	int x;//我是那個點
	int y;
	int steps;//走了多少步
	
	step(int xx,int yy,int _s ):x(xx),y(yy),steps(_s){}
};
queue<step> q;
int visited[5][5]={0};

int main()
{
	step s(0,0,1);
	q.push(s);
	visited[0][0]=1;
	while(!q.empty())
	{
		step s1 = q.front();
		if(s1.x ==4 && s1.y==4)//到終點了 
		{
			cout<<s1.steps<<endl;
			return 0;
		}
		else{
			if(s1.x-1>=0)
			{
				q.push(step(s1.x-1,s1.y,s1.steps+1));
				visited[s1.x-1][s1.y]=1;
			}
			if(s1.x+1<=4)
			{
				q.push(step(s1.x+1,s1.y,s1.steps+1));
				visited[s1.x+1][s1.y]=1;
			}
			if(s1.y-1>=0)
			{
				q.push(step(s1.x,s1.y-1,s1.steps+1));
				visited[s1.x][s1.y-1]=1;
			}
			if(s1.y+1<=4)
			{
				q.push(step(s1.x,s1.y+1,s1.steps+1));
				visited[s1.x][s1.y+1]=1;
			}
			q.pop();
		} 
	}
	return 0; 
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章