1. 程式人生 > >迷宮路徑【bfs+路徑】

迷宮路徑【bfs+路徑】

迷宮問題
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 28881 Accepted: 16636

Description

定義一個二維陣列: 
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)

真TM水;

AC程式碼:

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

int mapp[10][10] ;
bool vis[10][10];
int fx[4]={0,0,1,-1};
int fy[4]={1,-1,0,0};

struct Node{
	int x;
	int y;
	int step;//設定步數標記,方便輸出檢測
};

bool judge(int x,int y){
	if(x<0||y<0||y>4||x>4||mapp[x][y]||vis[x][y]){
		return false;
	}
	return true;
}

void bfs(int x,int y){
	 memset(vis,false,sizeof(vis));
	 vis[0][0]=true;
	 Node pr;
	 pr.step=0;
	 pr.x=x;
	 pr.y=y;
	 queue<Node>Q;
	 queue<Node>qq;//存路徑
	 qq.push(pr);
	 Q.push(pr);
	 while(!Q.empty()){
	 	pr=Q.front();
	 	Q.pop();
	 	if(pr.x==4&&pr.y==4){
	 		break ;
		 }
		 for(int i=0;i<4;i++){
		 	Node pn;
		 	pn.x=pr.x+fx[i];
		 	pn.y=pr.y+fy[i];
		 	if(judge(pn.x,pn.y)){
		 		pn.step=pr.step+1;
		 		vis[pn.x][pn.y]=true;
		 		Q.push(pn);
		 		qq.push(pn);
			 }
		 }
	 }
	 int i=0; 
	 while(!qq.empty()){
	 	Node k;
		 k=qq.front();
		 qq.pop(); 
	 	 if(k.step==i){//輸出檢測
	 	 	cout<<"("<<k.x<<", "<<k.y<<")"<<endl;
	 	 	i++;
		  }
	 }
}

int main(){
	for(int i=0;i<5;i++){
		for(int j=0;j<5;j++)
		cin>>mapp[i][j];
	}
	bfs(0,0);
	return 0;
}