题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=58
本题要考虑到起点与终点重合的特殊情况,本题不能通过改变地图已通过的道路为1,因为有多组测试数据,这样会破坏到下一次程序执行,地图无法恢复。因此要开一个bool数组去记录走过的道路
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int mp[9][9]={ 1,1,1,1,1,1,1,1,1
,1,0,0,1,0,0,1,0,1
,1,0,0,1,1,0,0,0,1
,1,0,1,0,1,1,0,1,1
,1,0,0,0,0,1,0,0,1
,1,1,0,1,0,1,0,0,1
,1,1,0,1,0,1,0,0,1
,1,1,0,1,0,0,0,0,1
,1,1,1,1,1,1,1,1,1};
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
struct node
{
int x,y;
int step;
};
node New,now;
node start;
int a,b,c,d;
queue<node>q;
bool vis[9][9];
int bfs()
{
if(start.x==c&&start.y==d)
return 0;
q.push(start);
vis[start.x][start.y]=true;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<4;i++)
{
New.x=now.x+dx[i];
New.y=now.y+dy[i];
New.step=now.step+1;
if(New.x<=8&&New.x>=0&&New.y<=8&&New.y>=0&&mp[New.x][New.y]==0&&!vis[New.x][New.y])
{
vis[New.x][New.y]=true;
q.push(New);
}
if(New.x==c&&New.y==d)
return New.step;
}
}
return -1;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
memset(vis,false,sizeof(vis));
scanf("%d%d%d%d",&a,&b,&c,&d);
start.x=a;
start.y=b;
start.step=0;
while(!q.empty())
q.pop();
int ans=bfs();
if(ans>=0)
cout<<ans<<endl;
}
return 0;
}