问题描述:
给定一个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 3Sample Output
no yes题目题意:题目给我们一个图,问我们能否在转弯不大于K次到达终点(第一次的方向随意)
题目分析:BFS 我们需要在结构体加入记录拐弯次数的step,然后每一次走到不能走到的时候(每一个方向下面,写一个循环),再拐弯。
这个题目的输入有变化,和我们一般思维不同,输入的是y x 坐标。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=110;
struct note
{
int x,y;
int step;
bool operator==(const note &a) const {
return x==a.x&&y==a.y;
}
}s,e;
queue<struct note> que;
char mmap[maxn][maxn];
char vis[maxn][maxn];
bool flag;
int n,m,k,dx,dy;
int Next[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
void bfs()
{
while (que.size()) que.pop();
s.step=0;
que.push(s);
vis[s.x][s.y]=true;
while (que.size()) {
struct note cur,next;
cur=que.front();
que.pop();
if (cur==e&&cur.step<=k+1) { flag=true; return; }//因为第一次方向任意,可以相当于多拐一次
for (int i=0;i<4;i++) {
dx=cur.x+Next[i][0];
dy=cur.y+Next[i][1];
next.step=cur.step+1;
while (dx>=0&&dx<n&&dy>=0&&dy<m&&mmap[dx][dy]=='.') {//每一次走到尽头,这里面的是方向朝一个方向的
if (!vis[dx][dy]) {//注意这个不能加到循环里面判断,因为可以重复走以前的地方
vis[dx][dy]=true;
next.x=dx,next.y=dy;
if (next==e&&next.step<=k+1) { flag=true; return;}
que.push(next);
}
dx+=Next[i][0];
dy+=Next[i][1];
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while (t--) {
scanf("%d%d",&n,&m);
memset (mmap,0,sizeof (mmap));
for (int i=0;i<n;i++)
scanf("%s",mmap[i]);
scanf("%d%d%d%d%d",&k,&s.y,&s.x,&e.y,&e.x);
s.x--,s.y--,e.x--,e.y--;//我的图是从0开始的,所以--
memset (vis,false,sizeof (vis));
flag=false;
bfs();
if (flag)
printf("yes\n");
else
printf("no\n");
}
return 0;
}