题目链接:hdu1728
还是bfs走迷宫, 但不再是求最短路,而是问能不能在k次转向内从出发点走到目标点.
初始方向不计入次数,可以直接把四个方向全push
队列节点的次数都限制在k次以内,大于k就不用push了
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 110;
struct node {
int turn, dir, x, y;
node() {}
node(int t, int d, int _x, int _y):turn(t), dir(d), x(_x), y(_y) {}
friend bool operator<(const node &a, const node &b) {
return a.turn < b.turn;
}
};
char mp[MAXN][MAXN];
int book[4][MAXN][MAXN];
int nx[] = {-1, 0, 1, 0};
int ny[] = {0, 1, 0, -1};
bool bfs(int k, int sx, int sy, int ex, int ey, int m, int n) {
priority_queue<node> q;
memset(book, 0x3f, sizeof(book));
q.push(node(0, 0, sx, sy));
q.push(node(0, 1, sx, sy));
q.push(node(0, 2, sx, sy));
q.push(node(0, 3, sx, sy));
while (!q.empty()) {
node t = q.top();
q.pop();
if (t.x == ex && t.y == ey)
return true;
for (int i = 0; i < 4; i++) {
int tx = t.x + nx[i];
int ty = t.y + ny[i];
if (tx < 1 || tx > m || ty < 1 || ty > n || mp[tx][ty] == '*')
continue;
int nturn = t.turn;
if (i != t.dir)
nturn++;
if (nturn <= k && nturn < book[i][tx][ty]) {
q.push(node(nturn, i, tx, ty));
book[i][tx][ty] = nturn;
}
}
}
return false;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int m, n;
scanf("%d%d", &m, &n);
getchar();
for (int i = 1; i <= m; i++)
fgets(mp[i]+1, MAXN, stdin);
int k, sx, sy, ex, ey;
scanf("%d%d%d%d%d", &k, &sx, &sy, &ex, &ey);
puts(bfs(k, sy, sx, ey, ex, m, n)?"yes":"no");
}
return 0;
}