概述
POJ1324
该题在BFS的基础上加入了状态压缩;
由于蛇不能碰到自己的身体,因此每一步状态需要记录身体的位置;如果直接使用int记录身体每一段坐标(x, y),内存消耗将非常大;
考虑这么一种压缩:移动过程中蛇身体的每一段的下一步位置是其前一段的当前位置,因此可以从蛇头位置往后回推蛇身的位置;另外,BFS的过程中是一定会记录移动方向的,记录身体的每一段的移动方向,由当前某一段身体位置往其反方向移动就可得到移动前其后一段的位置,因此可考虑记录身体每一段的下一步移动方向的反方向,这么做将状态压缩到了4*L个,同时状态压缩的按位移动操作效率远高于用int记录位置时对位置的修改
AC Code
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
struct xx {
int x, y;
} body[10];
struct node {
int x, y;
int body_move;
int step;
};
int stone[25][25];
int vis[25][25][1<<14];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
int reverse_move[4] = {1, 0, 3, 2};
int n, m, L;
int del;
bool check_body(node p, int _x, int _y)
{
int x = p.x, y = p.y;
for(int i=2; i<=L; ++i) {
int t = 0;
if(p.body_move&1) t += 1;
p.body_move >>= 1;
if(p.body_move&1) t += 2;
p.body_move >>= 1;
x += dx[t];
y += dy[t];
if(_x == x && _y == y)
return false;
}
return true;
}
int bfs(node st)
{
memset(vis, 0, sizeof(vis));
queue<node> que;
que.push(st);
while(!que.empty()) {
node p = que.front(); que.pop();
if(p.x == 1 && p.y == 1){
return p.step;
}
node _p;
for(int i=0; i<4; ++i) {
int x = p.x + dx[i];
int y = p.y + dy[i];
if(x<=0 || y<=0 || x>m || y>n || stone[x][y] ||!check_body(p, x, y)) continue;
_p.x = x;
_p.y = y;
_p.body_move = ((p.body_move<<2)&del) | reverse_move[i];
if(vis[y][x][_p.body_move]) continue;
vis[y][x][_p.body_move] = 1;
_p.step = p.step + 1;
que.push(_p);
}
}
return -1;
}
int main()
{
int K, x, y, cas=0;
while(scanf("%d%d%d", &n, &m, &L)){
if(n==0 && m==0 && L==0) break;
for(int i=1; i<=L; ++i) scanf("%d%d", &body[i].y, &body[i].x);
scanf("%d", &K);
memset(stone, 0, sizeof(stone));
for(int i=1; i<=K; ++i) {
scanf("%d%d", &y, &x);
stone[x][y] = 1;
}
del = (1<<((L-1)*2))-1;
node st;
st.x = body[1].x; st.y = body[1].y;
st.body_move = 0; st.step = 0;
for(int i=2; i<=L; ++i) {
for(int j=0; j<4; ++j) {
x = body[i-1].x + dx[j];
y = body[i-1].y + dy[j];
if(x == body[i].x && y == body[i].y)
st.body_move |= j<<((i-2)*2);
}
}
printf("Case %d: %d\n", ++cas, bfs(st));
}
return 0;
}