有一条蛇蜿蜒在洞穴里面,出口为(1,1),问(蛇头)走出洞口的最小步数。走的过程不能碰到自己的身体也不能碰到石头。蛇头每移动一格,身体也要相应的移动一格。(注意:貌似当前蛇头不能移动到当前蛇尾的位置)
由于蛇身占得位置太大,保存起来不方便,于是只用保存蛇头的位置,另外开一个二进制的串来保存其他身体块相对于上一块身体的位置,二进制的串每两位表示一个位置(也相当于4进制,每一个数表示一个方向)
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node
{
int x,y,bd,stp;
Node(){}
Node(int a,int b,int c,int d)
{x = a; y = b; bd = c; stp = d;}
}s;
int vis[21][21][1<<14];//头的位置在(x,y),身体相对于上一块的位置
int n,m,L,mp[21][21],a[10][2];
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int hash[4] = {0,1,2,3};
int cas;
void init()
{
memset(mp,0,sizeof mp);
cas++;
}
bool inarea(int i,int j)
{
if(i < 1||j < 1||i > n||j > m) return false;
else return true;
}
bool check(int tx,int ty,Node u)
{
int x = u.x,y = u.y,pos[10],bd = u.bd;
if(tx == x&&ty == y) return false;
for(int i = L-1; i >= 1; i--)
{
pos[i] = bd&3;
bd >>= 2;
}
for(int i = 1; i < L; i++)
{
int k = hash[pos[i]];//还原方向
x = x+dir[k][0],y = y+dir[k][1];
if(tx == x&&ty == y) return false;
}
return true;
}
int bfs()
{
if(s.x == 1&&s.y == 1) return 0;
queue<Node> Q;
Q.push(s);
vis[s.x][s.y][s.bd] = cas;
while(!Q.empty())
{
Node u = Q.front();
Q.pop();
for(int i = 0; i < 4; i++)
{
int tk,tx = u.x + dir[i][0],ty = u.y + dir[i][1],tbd = u.bd,tstp = u.stp+1;
if(mp[tx][ty]||!inarea(tx,ty)||!check(tx,ty,u)) continue;
if(i == 0) tk = 2;
if(i == 1) tk = 3;
if(i == 2) tk = 0;
if(i == 3) tk = 1;
tbd = (u.bd>>2) + (tk<<(2*L-4));
if(vis[tx][ty][tbd] == cas) continue;
if(tx == 1&&ty == 1) return tstp;
vis[tx][ty][tbd] = cas;
Q.push(Node(tx,ty,tbd,tstp));
}
}
return -1;
}
int main()
{
while(scanf("%d%d%d",&n,&m,&L) != EOF&&n+m+L)
{
init();
int k,x,y,tx,ty,f,st = 0;
for(int i = 1; i <= L; i++)
scanf("%d%d",&a[i][0],&a[i][1]);
s.x = a[1][0],s.y = a[1][1],s.stp = 0;
for(int i = 1; i < L; i++)
{
x = a[i][0],y = a[i][1];
tx = a[i+1][0],ty = a[i+1][1];
if(tx == x)
{
if(ty == y+1) f = 1;
else f = 3;
}
else
{
if(tx == x-1) f = 0;
else f = 2;
}
st = (st<<2)+f;
}
s.bd = st;
scanf("%d",&k);
for(int i = 1; i <= k; i++)
{
scanf("%d%d",&x,&y);
mp[x][y] = 1;
}
printf("Case %d: %d\n",cas,bfs());
}
}