hdu1732 Push Box (bfs)

三个箱子的推箱子。

节点保存人的坐标,三个箱子的坐标和整个地图。

判重用一个8维bool数组,表示人的坐标和三个箱子的坐标。

注意当箱子的前方还有箱子的时候不能前进。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>

using namespace std;

struct Node{
	int x, y;
	int step;
	char map[9][9];
	int box[3][2];
	Node() {
		x = y = step = 0;
		memset(map, 0, sizeof(map));
		memset(box, 0, sizeof(box));
	}
}s, cur, nex;

int n, m;
int dir[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
bool vis[9][9][9][9][9][9][9][9];

bool done() {
	return s.map[cur.box[0][0]][cur.box[0][1]] == '@'
		&& s.map[cur.box[1][0]][cur.box[1][1]] == '@'
		&& s.map[cur.box[2][0]][cur.box[2][1]] == '@';
}

bool check(int x, int y) {
	return (x >= 0 && x < n && y >= 0 && y < m && s.map[x][y] != '#');
}

int bfs() {
	memset(vis, 0, sizeof(vis));
	queue<Node> q;
	q.push(s);
	vis[s.x][s.y][s.box[0][0]][s.box[0][1]][s.box[1][0]][s.box[1][1]][s.box[2][0]][s.box[2][1]] = 1;
	while (!q.empty()) {
		cur = q.front();
		q.pop();
		if (done()) return cur.step;
		for (int i = 0; i < 4; i++) {
			nex = cur;
			int nx = cur.x + dir[i][0];
			int ny = cur.y + dir[i][1];
			if (!check(nx, ny)) continue;
			if (vis[nx][ny][nex.box[0][0]][nex.box[0][1]][nex.box[1][0]][nex.box[1][1]][nex.box[2][0]][nex.box[2][1]])
				continue;
			if (nex.map[nx][ny] == '*') {
				int bx = nx + dir[i][0];
				int by = ny + dir[i][1];
				if ((!check(bx, by)) || nex.map[bx][by] == '*') continue;
				int box;
				for (box = 0; box < 3; box++)
					if (nex.box[box][0] == nx && nex.box[box][1] == ny)
						break;
				nex.map[bx][by] = '*';
				nex.map[nx][ny] = nex.map[cur.x][cur.y] = '.';
				if (s.map[cur.x][cur.y] == '@') nex.map[cur.x][cur.y] = '@';
				if (s.map[nx][ny] == '@') nex.map[nx][ny] = '@';
				nex.box[box][0] = bx;
				nex.box[box][1] = by;
				if ((vis[nx][ny][nex.box[0][0]][nex.box[0][1]][nex.box[1][0]][nex.box[1][1]][nex.box[2][0]][nex.box[2][1]]))
					continue;
			}
			nex.step++;
			nex.x = nx, nex.y = ny;
			vis[nx][ny][nex.box[0][0]][nex.box[0][1]][nex.box[1][0]][nex.box[1][1]][nex.box[2][0]][nex.box[2][1]] = 1;
			q.push(nex);
		}
	}
	return -1;
}

int main() {
	while (~scanf("%d %d", &n, &m)) {
		s = Node();
		for (int i = 0; i < n; i++)
			scanf("%s", s.map[i]);
		int t = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (s.map[i][j] == 'X') {
					s.x = i;
					s.y = j;
				}
				if (s.map[i][j] == '*') {
					s.box[t][0] = i;
					s.box[t++][1] = j;
				}
			}
		}
		int ans = bfs();
		cout << ans << endl;
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值