您的位置:首页 > 编程语言 > C语言/C++

hdu 1728 逃离迷宫

2017-09-23 01:54 337 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728

题意:除了第一次任意方向走不算拐弯,问在最多拐k次的情况下能不能从(x1,y1)到(x2,y2)

思路:一次四个方向都走到头,并记录去过地方,将其入队,然后在出队的时候,如果四个方向有没去过的地方,往那边走就是拐弯,所以在入队的时候拐弯数就+1

(神tm最后一行输入,先输入的列,找了半天o(╥﹏╥)o)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxn 105

using namespace std;

int n, m, k, x1, x2, y1, y2;
char Map[maxn][maxn];
bool vis[maxn][maxn];
int x[] = {1, -1, 0, 0};
int y[] = {0, 0, 1, -1};

struct P
{
int x;
int y;
int num;
};

bool C(P pos)
{
if(pos.x < 1 || pos.x > n || pos.y < 1 || pos.y > m || Map[pos.x][pos.y] == '*')
return 0;
return 1;
}

bool BFS()
{
memset(vis, 0, sizeof(vis));
queue<P> Q;
P tmp;
tmp.x = x1, tmp.y = y1, vis[x1][y1] = 1, tmp.num = -1;
Q.push(tmp);

while(!Q.empty())
{
P cur = Q.front();
Q.pop();

if(cur.x == x2 && cur.y == y2 && cur.num <= k)
return 1;

for(int i = 0; i < 4; i++)
{
P pos;
pos.x = cur.x + x[i];
pos.y = cur.y + y[i];
while(C(pos))
{
// printf("%d %d %d %d\n", pos.x, pos.y, cur.x, cur.y);
if(!vis[pos.x][pos.y])
{
vis[pos.x][pos.y] = 1;
pos.num = cur.num + 1;
Q.push(pos);
}
pos.x += x[i];
pos.y += y[i];
}
}
}
return 0;
}

int main()
{
int t;
cin >> t;
while(t--)
{
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> Map[i][j];
}
}
scanf("%d %d %d %d %d", &k, &y1, &x1, &y2, &x2);

if(BFS())
cout << "yes" << endl;
else
cout << "no" << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ bfs hdu