易水人去,明月如霜。
Description
Input
只包含4個整數,它們彼此用空格隔開,分別爲xp,yp,xs,ys。並且它們的都小於10000000。
Output
含一個整數,表示從點p到點s至少需要經過的馬步移動次數。
Sample Input
Sample Output
代碼:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int read()
{
char ch;int s=0,f=1;ch=getchar();
while(ch>'9'||ch<'0') { if(ch=='-') f*=-1; ch=getchar(); }
while(ch<='9'&&ch>='0') s=s*10+ch-48,ch=getchar();
return s*f;
}
struct node {
int x,y;
};
int x,y;
int xp,yp,xs,ys;
int ans=0;
int dis[105][105];
int xx[8]={1,1,-1,-1,2,2,-2,-2},yy[8]={2,-2,2,-2,1,-1,1,-1};
int qx[10005],qy[10005];
void bfs()
{
memset(dis,-1,sizeof(dis));
dis[x][y]=0;
queue<node> q;
node s; s.x=x,s.y=y;
q.push(s);
while(!q.empty())
{
node now=q.front();q.pop();
for(int i=0;i<8;i++)
{
int dx,dy; dx=now.x+xx[i],dy=now.y+yy[i];
if(dx<0||dy<0||dx>100||dy>100) continue;
if(dis[dx][dy]!=-1) continue ;
dis[dx][dy]=dis[now.x][now.y]+1;
node dd; dd.x=dx,dd.y=dy;
q.push(dd); if(dx==50&&dy==50) return ;
}
}
}
int main()
{
xp=read(),yp=read(),xs=read(),ys=read();
x=abs(xp-xs),y=abs(yp-ys);
while(x+y>=50)
{
if(x<y) swap(x,y);
if(x-4>=2*y) x-=4;
else x-=4,y-=2;
ans+=2;
}
x+=50,y+=50;
bfs();
printf("%d\n",ans+dis[50][50]);
return 0;
}