POJ3322 Bloxorz I BFS

题目链接

http://poj.org/problem?id=3322

分析

每次操作,地图不会改变,变化的坐标及放置方式可以设为状态,进行BFS。

预处理出各种放置方式下,向各个方向移动后状态的变化情况。

AC代码

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

using namespace std;

const int maxn = 505;
const int nxt[4][2] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
const int next_x[3][4] = {{0, -2, 0, 1}, {0, -1, 0, 1}, {0, -1, 0, 2}};
const int next_y[3][4] = {{-2, 0, 1, 0}, {-1, 0, 2, 0}, {-1, 0, 1, 0}};
const int next_z[3][4] = {{1, 2, 1, 2}, {0, 1, 0, 1}, {2, 0, 2, 0}};

struct State {
	int x, y, z;

	bool operator == (const State& rhs) const {
		return x == rhs.x && y == rhs.y && z == rhs.z;
	}
} st, ed;

int n, m, d[maxn][maxn][3];
char map[maxn][maxn];
queue<State> q;

inline int judge(int x, int y) {
	return x >= 1 && x <= n && y >= 1 && y <= m;
}

inline int judge(State s) {
	if (!judge(s.x, s.y)) return 0;
	if (map[s.x][s.y] == '#') return 0;
	if (!s.z && map[s.x][s.y] != '.') return 0;
	if (s.z == 1 && map[s.x][s.y + 1] == '#') return 0;
	if (s.z == 2 && map[s.x + 1][s.y] == '#') return 0;
	return 1;
}

inline int bfs() {
	memset(d, -1, sizeof(d));
	while (!q.empty()) q.pop();
	d[st.x][st.y][st.z] = 0;
	q.push(st);
	while (!q.empty()) {
		State s = q.front(), ns;
		q.pop();
		if (s == ed) return d[s.x][s.y][s.z];
		for (int i = 0; i < 4; ++i) {
			ns.x = s.x + next_x[s.z][i];
			ns.y = s.y + next_y[s.z][i];
			ns.z = next_z[s.z][i];
			if (!judge(ns)) continue;
			if (d[ns.x][ns.y][ns.z] == -1) {
				d[ns.x][ns.y][ns.z] = d[s.x][s.y][s.z] + 1;
				q.push(ns);
			}
		}
	}
	return 0;
}

int main() {
	while (scanf("%d%d", &n, &m) == 2 && !(!n && !m)) {
		for (int i = 1; i <= n; ++i) scanf("%s", map[i] + 1);
		for (int i = 1; i <= n; ++i)
			for (int j = 1; j <= m; ++j) {
				if (map[i][j] == 'O')
					ed.x = i, ed.y = j, ed.z = 0, map[i][j] = '.';
				else if (map[i][j] == 'X') {
					for (int k = 2; k < 4; ++k) {
						int x = i + nxt[k][0], y = j + nxt[k][1];
						if (judge(x, y) && map[x][y] == 'X') {
							st.x = i, st.y = j, st.z = k - 1;
							map[i][j] = map[x][y] = '.';
							break;
						}
					}
					if (map[i][j] == 'X')
						st.x = i, st.y = j, st.z = 0, map[i][j] = '.';
				}
			}
		int ans = bfs();
		if (ans) printf("%d\n", ans);
		else printf("Impossible\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值