题意:
有一个游戏,给你一个n*m的地图,让你找到‘F’所在的位置,但是没这么简单,如
果你知道从(1,1)开始走到‘F’所在的位置的话,你就输出从(1,1)到终点的
转向,分别是’R’,’L’,’D’,’U’,如果是这样的话也是很简单的,不过游戏的有趣之处也在
这里,你发送一个转向,系统会给你转向之后的坐标,不过这四个转向有可能交换,
交换也只有两种可能,现在问题就是这样,你能愉快的输出吗?
思路:
看似很复杂的题目却是感觉起来很新颖,我们求出一个路径直接就是bfs,但是有趣的
是该怎么处理转向的问题,其实在每次转向之后我们可以判断系统给出的坐标是否是
正常的,否则的话就转换原来的转向。
- 注意:输出要立即输出,用到了:fflush(stdout)
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 105;
struct P
{
int x,y;
}now,next;
int n,m;
int s = 0,e = 0;
char str[maxn][maxn];
int vis[maxn][maxn];
int pre[maxn][maxn][2];
int step[30005][2],pos;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
char to[4] = {'R','L','D','U'};
void bfs()
{
memset(vis,0,sizeof(vis));
queue<P>q;
now.x = 1,now.y = 1;
q.push(now);
vis[1][1] = true;
pos = 0;
pre[1][1][0] = 1;
pre[1][1][1] = 1;
while(!q.empty()) {
now = q.front();
if(str[now.x][now.y] == 'F') break;
q.pop();
for(int i = 0;i < 4; i++) {
next.x = dx[i] + now.x;
next.y = dy[i] + now.y;
if(next.x >= 1 && next.x <= n && next.y >= 1 && next.y <= m && str[next.x][next.y] != '*') {
if(!vis[next.x][next.y]) {
vis[next.x][next.y] = true;
q.push(next);
pre[next.x][next.y][0] = now.x;
pre[next.x][next.y][1] = now.y;
}
}
}
}
}
void path()
{
pos = 0;
while(1) {
step[pos][0] = s;
step[pos][1] = e;
int tx = s,ty = e;
s = pre[tx][ty][0];
e = pre[tx][ty][1];
pos++;
if(s == 1 && e == 1) {
step[pos][0] = s;
step[pos][1] = e;
break;
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d%d",&n,&m);
for(int i = 1;i <= n; i++) {
scanf("%s",str[i]+1);
if(s == 0 && e == 0) {
for(int j = 1;j <= m; j++) {
if(str[i][j] == 'F') {
s = i;
e = j;
}
}
}
}
bfs();
path();
while(pos > 0) {
int flag = -1;
for(int i = 0;i < 4; i++) {
int xx = step[pos][0] + dx[i];
int yy = step[pos][1] + dy[i];
if(xx == step[pos-1][0] && yy == step[pos-1][1])
flag = i;
}
printf("%c\n",to[flag]);
fflush(stdout);
int x,y;
scanf("%d%d",&x,&y);
if(x == step[pos-1][0] && y == step[pos-1][1]) pos--;
else {
if(to[flag] == 'L' || to[flag] == 'R') swap(to[0],to[1]);
else swap(to[2],to[3]);
}
}
return 0;
}

本文介绍了一款迷宫游戏的路径寻找算法,利用广度优先搜索(BFS)找到从起点到终点的路径,并通过判断系统反馈来修正转向指令。文章详细解释了如何通过BFS算法构建路径以及如何处理转向问题。
609

被折叠的 条评论
为什么被折叠?



