【搜索】JZOJ_3319 LOJ_2686 「BalticOI 2013」雪地足迹 Tracks in the Snow

题意

在一片长方形的草地上,有 2 2 2种动物——兔子和狐狸活动。兔子走过草地会留下 R R R,狐狸走过草地会留下 F F F。每只动物从左上角进入草地,从右下角走出草地。其间,它可以上下左右乱跳(可以重复),经过的格子会被覆盖上它的脚印。每次草地上最多只有一只动物。求出最少有几只动物。

思路

第一次从左上角找联通块,那么这就是最后一只动物走的足迹,为了保证答案最优,找到联通块之后,把它取反,代表最后一只动物覆盖了倒数第二只动物的足迹,再找联通块,找到了倒数第二只动物的足迹,以此类推。

代码

#include<queue>
#include<cstdio>
#include<cstring>

const int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};
int n, m, ans;
int a[4001][4001], v[4001][4001];
char c[4001];
std::queue<std::pair<int, int> > q[2];

bool check(int x, int y) {
	return x > 0 && x <= n && y > 0 && y <= m && a[x][y] && !v[x][y];
}

bool bfs(int s) {
	bool f = 0;
	while (q[s].size()) {
		int x = q[s].front().first, y = q[s].front().second;
		q[s].pop();
		for (int i = 0; i < 4; i++) {
			if (check(x + dx[i], y + dy[i])) {
				v[x + dx[i]][y + dy[i]] = 1;
				if (a[x][y] == a[x + dx[i]][y + dy[i]]) q[s].push(std::make_pair(x + dx[i], y + dy[i]));
				else q[s ^ 1].push(std::make_pair(x + dx[i], y + dy[i])), f = 1;
			}
		}
	}
	return f;
}

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n; i++) {
		scanf("%s", c + 1);
		for (int j = 1; j <= m; j++) {
			if (c[j] == 'R') a[i][j] = 1;
			else if (c[j] == 'F') a[i][j] = 2;
			else a[i][j] = 0;
		}
	}
	q[0].push(std::make_pair(1, 1));
	v[1][1] = 1;
	for (int i = 0; bfs(i); i ^= 1, ans++);
	printf("%d", ans + 1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值