逃离迷宫
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12621 Accepted Submission(s): 3019
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对应行。
第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
参考代码
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<string> 6 #include<cmath> 7 #include<queue> 8 using namespace std; 9 int m,n,x2,y2,k; 10 char map[105][105]; 11 int vis[105][105];//标记走过,顺便标记这个位置上走过的,拐了几个弯 12 int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}}; 13 struct Node 14 { 15 int x,y,step,fx; 16 }; 17 int bfs(int x1,int y1) 18 {int fangxiang,i; 19 Node now,eed; 20 vis[x1][y1]=0;//没走过的都标记为-1 21 queue<Node>Q; 22 eed.x=x1;eed.y=y1;eed.step=0;eed.fx=0; 23 Q.push(eed); 24 while(!Q.empty()) 25 { 26 now=Q.front(); 27 Q.pop(); 28 if(now.x==x2 && now.y==y2 && now.step<=k) 29 return 1; 30 for(i=0;i<4;i++) 31 { 32 eed.x=now.x+dir[i][0];eed.y=now.y+dir[i][1]; 33 fangxiang=i+1;//1代表向左走,2代表向上走,3代表向右走,4代表向下走; 34 if(now.fx==0)//一下三个判断是判断和之前的方向是否一致 35 {eed.fx=fangxiang;eed.step=0;} 36 else if(now.fx!=fangxiang) 37 { 38 eed.step=now.step+1;eed.fx=fangxiang;//方向不一致的话,加上1 39 } 40 else {eed.step=now.step;eed.fx=now.fx;} 41 if(eed.x>=1 && eed.x<=m && eed.y>=1 && eed.y<=n && eed.step<=k && map[eed.x][eed.y]=='.') 42 { 43 if(vis[eed.x][eed.y]!=-1 && eed.step<=vis[eed.x][eed.y]) 44 {//如果这个点被走过,但是下一个走的拐的弯比前一个少的话,依然下一个能走,顺便记录拐的弯数 45 Q.push(eed);vis[eed.x][eed.y]=eed.step; 46 } 47 else if(vis[eed.x][eed.y]==-1) 48 { 49 Q.push(eed);vis[eed.x][eed.y]=eed.step; 50 } 51 } 52 } 53 } 54 return 0; 55 } 56 int main() 57 { 58 int i,j,t,x1,y1; 59 cin>>t; 60 while(t--) 61 { 62 cin>>m>>n; 63 for(int i=1;i<=m;i++) 64 for(int j=1;j<=n;j++) 65 { 66 cin>>map[i][j]; 67 vis[i][j]=-1; 68 } 69 scanf("%d %d %d %d %d",&k,&y1,&x1,&y2,&x2); 70 if((x1==x2 && y1==y2)|| bfs(x1,y1)==1) 71 printf("yes "); 72 else printf("no "); 73 } 74 return 0; 75 }