nbsp; // 队头结点坐标出队
for (i=0; i<8; ++i)
{
next.x = cur.x + dx[i];
next.y = cur.y + dy[i];
if (next.x<0 || next.x>=n || next.y<0 || next.y>=n)
continue;
if (next.x==end_x && next.y==end_y) // 到达目标位置
return step[cur.x][cur.y]+1;
if (!vis[next.x][next.y])
{
vis[next.x][next.y] = 1;
step[next.x][next.y] = step[cur.x][cur.y] + 1; // 记录步数
q[rear++] = next; // 当前合法坐标位置入队
}
}
}
return -1; // 若搜索不成功,表示不可达
}
int main()
{
int nCase,sx,sy,tx,ty,size,i,j;
scanf("%d", &nCase);
while (nCase--)
{
scanf("%d", &size);
for (i=0;i<size;i++)
for (j=0;j<size;j++)
vis[i][j]=step[i][j]=0;
scanf("%d %d", &sx, &sy);
scanf("%d %d", &tx, &ty);
if (sx==tx && sy==ty)
{
printf("0\n");
}
else
{
printf("%d\n",BFS(sx,sy,tx,ty,size));
}
}
return 0;
}
(3)编程思路2。
用同一个队列来保存正向和逆向扩展的结点。开始时,将起点坐标和终点坐标同时入队列。这样,第1个出队的坐标是起点,正向搜索扩展队列;第2个出队的坐标是终点,逆向搜索扩展队列。…,两个方向的扩展依次交替进行。
由于