cf1063B Labyrinth BFS+双端队列

25 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值