逃離迷宮
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 31340 Accepted Submission(s): 7672
第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對應行。
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;
}