//超时
#include<stdio.h>
#include<string.h>int map[80][80],visit[80][80],count[80][80];
int w,h;
void dfs(int x1,int y1,int x2,int y2)
{
int queue[100000];
int x,y,q_i=0,q_f=0;
int que_f[80][80];//入队标志
memset(que_f,0,sizeof(que_f));
queue[q_i++]=x1;
queue[q_i++]=y1;//入队
count[x1][y1]=0;
while(q_i>q_f)
{
x1=queue[q_f++];
y1=queue[q_f++];
visit[x1][y1]=1;
//四个方向
for(x=x1;x>0&&!(visit[x-1][y1]);x--)//上走
{
if(x-1==x2&&y1==y2)
{
count[x-1][y1]=count[x1][y1]+1;
return;
}
if(map[x-1][y1])
{
x=-1;
visit[x-1][y1]=1;
}
else if(!que_f[x-1][y1])
{
count[x-1][y1]=count[x1][y1]+1;
queue[q_i++]=x-1;
queue[q_i++]=y1;//入队
que_f[x-1][y1]=1;
}
}
for(x=x1;x<h+1&&!visit[x+1][y1];x++)//下走
{
if(x+1==x2&&y1==y2)
{
count[x+1][y1]=count[x1][y1]+1;
return;
}
if(map[x+1][y1])
{
x=h+1;
visit[x+1][y1]=1;
}
else if(!que_f[x+1][y1])
{
count[x+1][y1]=count[x1][y1]+1;
queue[q_i++]=x+1;
queue[q_i++]=y1;//入队
que_f[x+1][y1]=1;
}
}
for(y=y1;y>0&&!visit[x1][y-1];y--)//左走
{
if(x1==x2&&y-1==y2)
{
count[x1][y-1]=count[x1][y1]+1;
return;
}
if(map[x1][y-1])
{
y=-1;
visit[x1][y-1]=1;
}
else if(!que_f[x1][y-1])
{
count[x1][y-1]=count[x1][y1]+1;
queue[q_i++]=x1;
queue[q_i++]=y-1;//入队
que_f[x1][y-1]=1;
}
}
for(y=y1;y<w+1&&!visit[x1][y+1];y++)//右走
{
if(x1==x2&&y+1==y2)
{
count[x1][y+1]=count[x1][y1]+1;
return;
}
if(map[x1][y+1])
{
y=h+1;
visit[x1][y+1]=1;
}
else if(!que_f[x1][y+1])
{
count[x1][y+1]=count[x1][y1]+1;
queue[q_i++]=x1;
queue[q_i++]=y+1;//入队
que_f[x1][y+1]=1;
}
}
}
}
int main()
{
int i,j,x1,y1,x2,y2;//w列,h行
char ch;
int Case=1,pair;
while(scanf("%d%d",&w,&h)&&h!=0&&w!=0)
{
getchar();
for(i=1;i<=h;i++)//存表
{
for(j=1;j<=w;j++)
{
scanf("%c",&ch);
if(ch=='X')
map[i][j]=1;
else
map[i][j]=0;
}
getchar();
}
printf("Board #%d:\n",Case);
pair =0;
while(scanf("%d%d%d%d",&y1,&x1,&y2,&x2)&&!(x1==0&&y1==0&&y2==0&&x2==0))
{
pair++;
memset(visit,0,sizeof(visit));
memset(count,0,sizeof(count));
dfs(x1,y1,x2,y2);
if(count[x2][y2]!=0)
printf("Pair %d: %d segments.\n",pair,count[x2][y2]);
else
printf("Pair %d: impossible.\n",pair);
}
Case++;
}
return 0;
}