cf1063B Labyrinth BFS+双端队列

版权声明:虽然是个蒟蒻但是转载还是要说一声的哟 https://blog.csdn.net/jpwang8/article/details/83065691

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;
}

猜你喜欢

转载自blog.csdn.net/jpwang8/article/details/83065691
今日推荐