Description
You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m m m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c . In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can’t move beyond the boundaries of the labyrinth.
Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.
Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property?
Solution
真是神奇的题目QAQ,怒掉rating的我好菜啊
十分简单的bfs。实际上我们只需要记录到达每个格子时x和y最大的状态,这样肯定不会更劣
网上给出的做法之一是双端队列,我们每次把纵向走的点插入队头,横向走的点插入队尾,这样就能保证入队顺序是x和y递增的顺序了
Code
#include <stdio.h>
#include <string.h>
#include <queue>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)
const int N=2005;
struct pos {
int x,y,xx,yy;
};
bool vis[N][N];
char str[N];
int n,m;
pos move(pos x,int k) {
if (k==0) return (pos) {x.x-1,x.y,x.xx,x.yy};
if (k==1) return (pos) {x.x+1,x.y,x.xx,x.yy};
if (k==2) return (pos) {x.x,x.y-1,x.xx-1,x.yy};
if (k==3) return (pos) {x.x,x.y+1,x.xx,x.yy-1};
}
void bfs(pos st) {
std:: deque <pos> que;
que.push_back(st); int ans=0;
for (;!que.empty();) {
pos now=que.front(); que.pop_front();
if (vis[now.x][now.y]) continue;
vis[now.x][now.y]=true; ans++;
if (now.x>1&&!vis[now.x-1][now.y]) que.push_front(move(now,0));
if (now.x<n&&!vis[now.x+1][now.y]) que.push_front(move(now,1));
if (now.xx>0&&now.y>1&&!vis[now.x][now.y-1]) que.push_back(move(now,2));
if (now.yy>0&&now.y<m&&!vis[now.x][now.y+1]) que.push_back(move(now,3));
}
printf("%d\n", ans);
}
int main(void) { int r,c,xx,yy;
scanf("%d%d%d%d%d%d",&n,&m,&r,&c,&xx,&yy);
rep(i,1,n) {
scanf("%s",str+1);
rep(j,1,m) vis[i][j]=str[j]=='*';
}
bfs((pos) {r,c,xx,yy});
return 0;
}

本文介绍了一款计算机游戏中的迷宫级别挑战,玩家需要在有限的左右移动次数内,从起点到达尽可能多的自由格子。文章详细解释了使用广度优先搜索(BFS)算法解决这一问题的方法,通过双端队列优化移动顺序,确保效率。
652

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



