hdu1324 Holedox Moving (bfs+状态压缩+A*)

题意:

一个贪吃蛇,地图上有障碍,问走到(1,1)的最少步数。

思路:

对于状态的表示,由于蛇身的方块一定是一个连着一个的,所以可以只记录蛇头的坐标,然后用一个2位的二进制数表示接下来每个方块的方向。

这样状态只有20*20*2^14种,不会超内存。

若当前贪吃蛇的状态为stat,接下来走的方向为pos,那么下一个状态就是:

pos = (pos + 2) % 4;
(stat >> 2) + (pos << ((l << 1) - 4));

将当前的步数step与当前坐标与(1,1)的曼哈顿距离dist相加,每次取队列中step+dist最小的扩展(A*)。


完整代码:

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

using namespace std;

struct Node{
	int x, y, step, stat;
	Node() {}
	Node(int a, int b, int c, int d) : x(a), y(b), step(c), stat(d) {}
	bool operator < (const Node &n) const {
		int dist = x + y - 2;
		int ndist = n.x + n.y - 2;
		return step + dist > n.step + ndist;
	}
};

int n, m, l, k;
int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int map[22][22];
bool vis[22][22][16388];
Node start;
int direction[11];
bool check(int x, int y, Node cur) {
	if (x < 1 || x > n || y < 1 || y > m || map[x][y] == 1) return false;
	for (int i = l - 1; i >= 1; i--) {
		direction[i] = cur.stat & 3;
		cur.stat >>= 2;
	}
	for (int i = 1; i < l; i++) {
		cur.x += dir[direction[i]][0];
		cur.y += dir[direction[i]][1];
		if (cur.x == x && cur.y == y) return false;
	}
	return true;
}

int bfs() {
	if (start.x == 1 && start.y == 1) return 0;
	memset(vis, 0, sizeof(vis));
	priority_queue<Node> q;
	q.push(start);
	vis[start.x][start.y][start.stat] = 1;
	while (!q.empty()) {
		Node cur = q.top();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int nx = cur.x + dir[i][0];
			int ny = cur.y + dir[i][1];
			if (!check(nx, ny, cur)) continue;
			int pos = (i + 2) % 4;
			int stat = (cur.stat >> 2) + (pos << ((l << 1) - 4));
			if (!vis[nx][ny][stat]) {
				vis[nx][ny][stat] = 1;
				if (nx == 1 && ny == 1) return cur.step + 1;
				q.push(Node(nx, ny, cur.step + 1, stat));
			}
		}
	}
	return -1;
}

int main() {
	int cas = 1;
	while (~scanf("%d %d %d", &n, &m, &l) && n && m && l) {
		memset(map, 0, sizeof(map));
		int x, y;
		scanf("%d %d", &x, &y);
		start = Node(x, y, 0, 0);
		int stat = 0;
		int prex = x, prey = y;
		int pos;
		for (int i = 1; i < l; i++) {
			scanf("%d %d", &x, &y);
			if (x == prex - 1) pos = 0;
			if (x == prex + 1) pos = 2;
			if (y == prey - 1) pos = 3;
			if (y == prey + 1) pos = 1;
			prex = x, prey = y;
			stat <<= 2;
			stat |= pos;
		}
		start.stat = stat;
		scanf("%d", &k);
		for (int i = 0; i < k; i++) {
			scanf("%d %d", &x, &y);
			map[x][y] = 1;
		}
		int ans = bfs();
		printf("Case %d: %d\n", cas++, ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值