我们假定给定的两个位置都是空地,初始时。gloria所面向的方向未定,她能够选择4个方向的不论什么一个出发,而不算成一次转弯。
gloria能从一个位置走到另外一个位置吗?
2 5 5 ...** *.**. ..... ..... *.... 1 1 1 1 3 5 5 ...** *.**. ..... ..... *.... 2 1 1 1 3
no yes
题解:沿着一个方向走究竟。用一个数组记录转弯次数。第45行加了个剪枝。由于用的是广搜,所以第一次到达时肯定是用转弯次数最少的时候,若此时转弯次数都超了那就不用继续搜索下去了。
时间从62ms降低到15ms。
#include <stdio.h>
#include <string.h>
#include <queue>
#define maxn 102
using std::queue;
char map[maxn][maxn];
int steps, m, n, step[maxn][maxn];
int mov[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
struct Node{
int x, y;
Node operator+(int i){
Node t;
t.x = x + mov[i][0];
t.y = y + mov[i][1];
return t;
}
};
bool check(int x, int y)
{
return x < m && x >= 0 && y < n && y >= 0
&& map[x][y] != '*';
}
bool BFS(int x, int y)
{
if(map[x][y] == 'T') return true;
memset(step, -1, sizeof(step));
Node now, t;
int i;
now.x = x; now.y = y;
queue<Node> Q;
Q.push(now);
while(!Q.empty()){
now = Q.front(); Q.pop();
for(i = 0; i < 4; ++i){
t = now + i;
while(check(t.x, t.y)){
//保证不反复入队。可能出现路线交叉的情况
if(step[t.x][t.y] == -1){
step[t.x][t.y] = step[now.x][now.y] + 1;
if(map[t.x][t.y] == 'T'){
if(step[t.x][t.y] <= steps) return 1;
return 0;
}
Q.push(t);
}
t = t + i;
}
}
}
return false;
}
int main()
{
int t, x1, y1, x2, y2, i;
scanf("%d", &t);
while(t--){
scanf("%d%d", &m, &n);
for(i = 0; i < m; ++i)
scanf("%s", map[i]);
scanf("%d%d%d%d%d", &steps, &y1, &x1, &y2, &x2);
--x1; --y1; --x2; --y2;
map[x2][y2] = 'T';
if(BFS(x1, y1)) puts("yes");
else puts("no");
}
return 0;
}版权声明:本文博客原创文章,博客,未经同意,不得转载。
原文:http://www.cnblogs.com/gcczhongduan/p/4746276.html