这个题,discuss里说可能数据比较水,我用了普遍认为正确的一个方向一直搜下去,用队列和优先队列都可以,没有区别。
#include <iostream>
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
const int maxn = 100 + 5;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int w,h;
bool vst[maxn][maxn];
char game[maxn][maxn];
struct node
{
int step;
int x,y;
bool friend operator <(node a,node b)
{
return a.step > b.step;
}
};
int BFS(int sx,int sy,int ex,int ey)
{
memset(vst,0,sizeof(vst));
queue<node> q;
node cur,next;
cur.step = 0;
cur.x = sx;
cur.y = sy;
vst[cur.x][cur.y] = true;
q.push(cur);
while(!q.empty())
{
cur = q.front();
if(cur.x == ex && cur.y == ey)
return cur.step;
q.pop();
for(int i=0;i<4;i++)
{
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
while(next.x>=0 && next.x<=h+1 && next.y >=0 && next.y<=w+1 && !vst[next.x][next.y] && game[next.x][next.y]==' ')
{
vst[next.x][next.y] = true;
next.step = cur.step + 1;
q.push(next);
next.x += dir[i][0];
next.y += dir[i][1];
}
}
}
return -1;
}
int main()
{
int CNT = 1;
while(scanf("%d%d",&w,&h)!=EOF&&(w||h))
{
memset(game,' ',sizeof(game));
for(int i=1;i<=h;i++)
{
getchar();
for(int j=1;j<=w;j++)
game[i][j] = getchar();
}
printf("Board #%d:\n",CNT++);
int sx,sy,ex,ey;
int cnt=1;
while(scanf("%d%d%d%d",&sy,&sx,&ey,&ex)!=EOF&&(ex||ey||sx||sy))
{
printf("Pair %d: ",cnt++);
game[ex][ey] = ' ';
int ans = BFS(sx,sy,ex,ey);
if(ans == -1)
printf("impossible.\n");
else
printf("%d segments.\n",ans);
game[ex][ey] = 'X';
}
printf("\n");
}
return 0;
}