1. 程式人生 > >2018年東北農業大學春季校賽D wyh的迷宮

2018年東北農業大學春季校賽D wyh的迷宮

給你一個n*m的迷宮,這個迷宮中有以下幾個標識:

s代表起點

t代表終點

x代表障礙物

.代表空地

現在你們涵哥想知道能不能從起點走到終點不碰到障礙物(只能上下左右進行移動,並且不能移動到已經移動過的點)。

輸入描述:

輸入第一行一個整數T(1<=T<=10)
接下來有T組測試資料,對於每一組測試資料,第一行輸入2個數n和m(1<=n,m<=500)
接下來n行,每行m個字元代表這個迷宮,每個字元都是上面4箇中的一種
資料保證只有一個起點和一個終點

輸出描述:

對於每一組測試資料,如果可以的話輸出YES,不可以的話輸出NO

示例1

輸入

1
3 5
s...x
x...x
...tx

輸出

YES
就是走迷宮,很好理解。注意YES跟NO是全大寫的就行了。

程式碼如下 :

#include <iostream>  
#include <cstring>  
#include <queue>  
using namespace std;
struct coordinate{
	int x,y;
}now,fresh;
char a[501][501];
int sx,sy,tx,ty,t,n,m;
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
int vis[501][501];
void dfs(int x,int y){
	memset(vis,0,sizeof(vis));
	queue<coordinate> s;
	now.x=x;
	now.y=y;
	vis[x][y]=1;
	s.push(now);
	while(!s.empty()){
		now=s.front();
		s.pop();
		for(int i=0;i<4;i++){		//四個方向走 
			fresh.x=now.x+dx[i];
			fresh.y=now.y+dy[i];
			while(1){
				if(fresh.x>=0&&fresh.x<n&&fresh.y>=0&&fresh.y<m&&a[fresh.x][fresh.y]!='x'){
					if(fresh.x==tx&&fresh.y==ty){
						cout<<"YES"<<endl;
						return ;
					}
					if(vis[fresh.x][fresh.y]==0){
						vis[fresh.x][fresh.y]=1;
						s.push(fresh);		//將沒有走完四個方向的放進佇列裡 
					}
					fresh.x+=dx[i];
					fresh.y+=dy[i];
				}
				else break;
			}
		}
	}
	cout<<"NO"<<endl;
}
int main()
{
//	ios::sync_with_stdio(false); 
	int t;
	cin>>t;
//	scanf("%d",&t);
	while(t--){
		cin>>n>>m;
//		scanf("&d%d",&n,&m);
		memset(a,0,sizeof(a));
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>a[i][j];
//				scanf("%c",&a[i][j]);
				if(a[i][j]=='s'){
					sx=i;sy=j;
				}
				if(a[i][j]=='t'){
					tx=i;ty=j;
				}
			}
			getchar();
		}
		dfs(sx,sy);		
	}
	
	return 0;
 }