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
题目大意:给定起点与终点,要求走到终点转弯的次数不能超过指定次数,第一次不算。
要注意的点:输入x1,y2,x2,y2时,x1代表的是列,y1代表的是行!
用深搜超时,改用广搜。刚开始的广搜是打算再结构体中定义两个坐标变量,转弯的次数,以及一个记录转弯方向的变量,想着每遍历一个点,判断当前走的方向与上次的方向相不相同,不相同就加一。但是好像过不了。找到一篇博客说了原因:链接 参考其他题解,几乎都是每次就往一个方向走到底,然后把遍历的点入队列,在遍历同一个方向的不同点时,其转弯的次数等于刚转到这个方向时转弯的次数。即碰到一个没有遍历的点,转弯的次数等于这个方向起点的转弯次数加一。可以参考下面的思路,取自https://blog.csdn.net/qq_40626497/article/details/81149915
*思路: 一条路到底,一直走一个方向下去,并把该方向上可以访问的点压入队列
* 然后每个方向都是如此
* 例 (x1,y1)=(0,0) -->a (x2,y2)=(0,2) -->b
* step1 a_-1 ._0 ._0 *_ *_
* *_ ._ *_ *_ ._
* b_ ._ ._ ._ ._
* ._ ._ ._ ._ ._
* *_ ._ ._ ._ ._
*
* step2 a_-1 ._0 ._0 *_ *_
* *_ ._1 *_ *_ ._
* b_ ._1 ._ ._ ._
* ._ ._1 ._ ._ ._
* *_ ._1 ._ ._ ._
*
* step3 a_-1 ._0 ._0 *_ *_
* *_ ._1 *_ *_ ._3
* b_2 ._1 ._2 ._2 ._2
* ._2 ._1 ._2 ._2 ._2
* *_ ._1 ._2 ._2 ._2
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
//给定起点与终点,要求走到终点转弯不能超过指定次数
int mov[4][2] = {0,1,0,-1,1,0,-1,0};
int t,m,n,x1,x2,y1,y2,k;
char mapp[110][110];
int vis[110][110];
struct node
{
int x,y,s;
};
bool Judge(int x,int y)
{
return x>=0&&x<m&&y>=0&&y<n&&mapp[x][y]=='.';
}
bool bfs()
{
queue<node>q;
node a,next,temp;
a.s = -1;//第一次不算
a.x = x1-1;
a.y = y1-1;
//a.w = -1;
vis[a.x][a.y] = 1;
q.push(a);
while(!q.empty())
{
a = q.front();
q.pop();
if(a.x==x2-1 && a.y==y2-1 &&a.s<=k)
return true;
for(int i = 0; i<4; i++)
{
next.x = a.x+mov[i][0];
next.y = a.y+mov[i][1];
while(Judge(next.x,next.y))
{
if(!vis[next.x][next.y])//如果没有遍历过
{
next.s = a.s+1;//转弯次数只等于第一次转弯道这个方向时的次数。 3.
vis[next.x][next.y] = 1;
q.push(next);
}
//往一个方向走时 1.
temp.x = next.x+mov[i][0];
temp.y = next.y+mov[i][1];
next = temp;//只改变坐标,不改变转弯次数。 2.
}
}
}
return false;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(int i = 0; i<m; i++)
{
scanf("%s",mapp[i]);
}
scanf("%d%d%d%d%d",&k,&y1,&x1,&y2,&x2);
memset(vis,0,sizeof(vis));
if(bfs())
printf("yes\n");
else
printf("no\n");
}
return 0;
}
/*
int dfs(int x,int y,int s)
{
if(x>=m || y>=n || mapp[x][y]=='*')
return 0;
if(s>k)
return 0;
if(x==x2-1&&y==y2-1)
return 1;
if(dfs(x+1,y,s+1)||dfs(x-1,y,s+1)||dfs(x,y-1,s+1)||dfs(x,y+1,s+1))
return 1;
}
*/