图论书上,BFS
蛇的爬动
Sample Input
5 6 4
4 1
4 2
3 2
3 1
3
2 3
3 3
3 4
4 4 4
2 3
1 3
1 4
2 4
4
2 1
2 2
3 4
4 2
0 0 0
Sample Output
Case 1: 9
Case 2: -1
Hint
In the above sample case, the head of Holedox can follows (4,1)->(5,1)->(5,2)->(5,3)->(4,3)->(4,2)->(4,1)->(3,1)->(2,1)->(1,1) to reach the square of exit with minimal number of step, which is nine.
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int dir[4][2]={-1,0,0,1,1,0,0,-1};
bool mark[21][21][1<<14];
int n,m,l;
struct node{
short x,y,t;
short state;
}a,b,qu[1<<20];
bool map[21][21];
short dz[3][3];
void bfs(){
int i,j,xx,yy,end=0,head=0,temp;
bool flag;
memset(mark,0,sizeof(mark));
a.t=0; qu[end++]=a;
while(head<end){
b=qu[head++];
if(b.x==1&&b.y==1){
printf("%d\n",b.t); return;
}
for(i=0;i<4;i++){
if(i==b.state%4)continue;
a=b; a.x+=dir[i][0]; a.y+=dir[i][1];
if(a.x>=1&&a.x<=n&&a.y>=1&&a.y<=m&&!map[a.x][a.y]){
xx=b.x;yy=b.y;flag=false;
for(j=1;j<l;j++){
temp=a.state%4; a.state=a.state/4;
xx+=dir[temp][0]; yy+=dir[temp][1];
if(a.x==xx&&a.y==yy) break;
}
if(j<l)continue;
a.t++;
a.state=b.state%(1<<((l-2)*2));
a.state=a.state*4+dz[b.x-a.x+1][b.y-a.y+1];
if(!mark[a.x][a.y][a.state]){
if(a.x==1&&a.y==1){
printf("%d\n",a.t);
return;
}
qu[end++]=a; mark[a.x][a.y][a.state]=1;
}
}
}
}
printf("-1\n");
}
int main(){
int i,j,st,x,y,v=1;
int p[8][2],b[9];
dz[0][1]=0;dz[1][2]=1;dz[2][1]=2;dz[1][0]=3;
while(scanf("%d%d%d",&n,&m,&l)&&n){
memset(map,0,sizeof(map));
scanf("%d%d",&a.x,&a.y);
p[0][0]=a.x;p[0][1]=a.y;
a.state=0;
for(i=1;i<l;i++){
scanf("%d%d",&p[i][0],&p[i][1]);
b[i]=dz[p[i][0]-p[i-1][0]+1][p[i][1]-p[i-1][1]+1];
}
for(i=l-1;i>=1;i--)
a.state=a.state*4+b[i];
scanf("%d",&st);
while(st--){
scanf("%d%d",&x,&y);
map[x][y]=true;
}
printf("Case %d: ",v++);
bfs();
}
}