HDU-1728 逃離迷宮(BFS)

逃離迷宮

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 31340    Accepted Submission(s): 7672


Problem Description
  給定一個m × n (m行, n列)的迷宮,迷宮中有兩個位置,gloria想從迷宮的一個位置走到另外一個位置,當然迷宮中有些地方是空地,gloria可以穿越,有些地方是障礙,她必須繞行,從迷宮的一個位置,只能走到與它相鄰的4個位置中,當然在行走過程中,gloria不能走到迷宮外面去。令人頭痛的是,gloria是個沒什麼方向感的人,因此,她在行走過程中,不能轉太多彎了,否則她會暈倒的。我們假定給定的兩個位置都是空地,初始時,gloria所面向的方向未定,她可以選擇4個方向的任何一個出發,而不算成一次轉彎。gloria能從一個位置走到另外一個位置嗎?
 

Input
  第1行爲一個整數t (1 ≤ t ≤ 100),表示測試數據的個數,接下來爲t組測試數據,每組測試數據中,
  第1行爲兩個整數m, n (1 ≤ m, n ≤ 100),分別表示迷宮的行數和列數,接下來m行,每行包括n個字符,其中字符'.'表示該位置爲空地,字符'*'表示該位置爲障礙,輸入數據中只有這兩種字符,每組測試數據的最後一行爲5個整數k, x1, y1, x2, y2 (1 ≤ k ≤ 10, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m),其中k表示gloria最多能轉的彎數,(x1, y1), (x2, y2)表示兩個位置,其中x1,x2對應列,y1, y2對應行。
 

Output
  每組測試數據對應爲一行,若gloria能從一個位置走到另外一個位置,輸出“yes”,否則輸出“no”。
 

Sample Input
2 5 5 ...** *.**. ..... ..... *.... 1 1 1 1 3 5 5 ...** *.**. ..... ..... *.... 2 1 1 1 3
 
Sample Output
no

yes



解答:

#include<iostream>  
#include<queue>
#include<cstdio>  
#include<cstring>  
#include<algorithm> 
#include<vector> 
#include<cmath>  
#include<sstream>
#include<cstdlib>
#include<map>
const int N =105;
int n,m,k;
int sx,sy,ex,ey;//起點和終點座標和轉彎最大次數 
int dir[4][2] = {{1,0},{-1,0},{0,-1},{0,1}}; 
struct position{
	int x,y,t;//座標,轉彎次數 
};

char d[N][N];
int vis[N][N];

using namespace std;
bool bfs(){
	queue<position> q;
	position temp;
	temp.x = sx;
	temp.y = sy;
	temp.t = -1;//第一次選擇方向不算
	q.push(temp);
	vis[sx][sy] = 1;
	while(!q.empty()){
			position now = q.front(); q.pop();
		if(now.x == ex&&now.y == ey&&now.t <= k){
			return true;
		}
		for(int i = 0 ;i<4;i++){
			position tmp;
			tmp.x = now.x+dir[i][0];
			tmp.y = now.y+dir[i][1];
			tmp.t = now.t;
			while(d[tmp.x][tmp.y]!='*'&&1<=tmp.x&&tmp.x<=m&&1<=tmp.y&&tmp.y<=n){
				if(vis[tmp.x][tmp.y] == 0)
				{
					tmp.t = now.t + 1;
					vis[tmp.x][tmp.y] = 1;
					q.push(tmp);
				}
				tmp.x+=dir[i][0];
				tmp.y+=dir[i][1];
				
			}
		} 
	}
	return false;
}
int main(){
	int T;
	cin>>T;
	for(int cases = 1;cases<=T;cases++){
		scanf("%d%d",&m,&n);
		//初始化
		memset(vis,0,sizeof(vis));
		//輸入圖
		for(int i =1;i<=m;i++){
			for(int j =1;j<=n;j++){
				scanf(" %c",&d[i][j]);//前面加個空格 
			}
		}
		
		cin>>k>>sy>>sx>>ey>>ex;
		if(bfs()) cout<<"yes"<<endl;
		else cout<<"no"<<endl;
	}
	
	return 0;
}



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