此题本人的解法速度不错,在STATISTICS中的第一页 :)
/*
* hdu-2757 ocean currents
* mike-w
* 2012-3-17
* ****************************************
* 通过此题,学习了边权只含0,1的图的
* 最短路的求法
* ****************************************
* 速度很快!小得意一下 :)
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 1111
#define Q_SIZE 11111
#ifndef true
#define true 1
#endif
#define valid(xx,yy) (xx>=0 && xx<row && yy>=0 && yy<col && !f[xx][yy])
char g[MAX_SIZE][MAX_SIZE];
int f[MAX_SIZE][MAX_SIZE];
int que[Q_SIZE][2],qhead,qtail,qlen;
int row,col,ncase;
int d[8][2]={-1,0, -1,1, 0,1, 1,1, 1,0, 1,-1, 0,-1, -1,-1};
int enque(int x,int y)
{
if(qlen==Q_SIZE)
return -1;
que[qtail][0]=x;
que[qtail][1]=y;
qtail=++qtail%Q_SIZE;
qlen++;
return 0;
}
int deque(int *x, int *y)
{
if(qlen==0)
return -1;
*x=que[qhead][0];
*y=que[qhead][1];
qhead=++qhead%Q_SIZE;
qlen--;
return 0;
}
int search(int sx, int sy, int tx, int ty)
{
int i,x0,y0,xx,yy,xxx,yyy;
memset(f,0,sizeof(f));
qhead=qtail=qlen=0;
f[sx][sy]=1;
enque(sx,sy);
x0=sx;y0=sy;
while(true)
{
xx=x0+d[g[x0][y0]][0];
yy=y0+d[g[x0][y0]][1];
if(!valid(xx,yy))
break;
enque(xx,yy);
f[xx][yy]=1;
if(f[tx][ty])
return f[tx][ty]-1;
x0=xx;
y0=yy;
}
while(deque(&x0,&y0)!=EOF)
{
for(i=0;i<8;i++)
{
xx=x0+d[i][0];
yy=y0+d[i][1];
if(valid(xx,yy))
{
enque(xx,yy);
f[xx][yy]=f[x0][y0]+1;
while(true)
{
xxx=xx+d[g[xx][yy]][0];
yyy=yy+d[g[xx][yy]][1];
if(!valid(xxx,yyy))
break;
enque(xxx,yyy);
f[xxx][yyy]=f[xx][yy];
xx=xxx;
yy=yyy;
}
}
}
if(f[tx][ty])
break;
}
return f[tx][ty]-1;
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("in","r",stdin);
#endif
int i,j,sx,sy,tx,ty;
while(scanf("%d%d",&row,&col)!=EOF)
{
for(i=0;i<row;i++)
scanf("%s",g[i]);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
g[i][j]-='0';
scanf("%d",&ncase);
while(ncase-->0)
{
scanf("%d%d%d%d",&sx,&sy,&tx,&ty);
sx--;sy--;tx--;ty--;
printf("%d\n",search(sx,sy,tx,ty));
}
}
return 0;
}