总时间限制: 1000ms 内存限制: 65535kB
描述
在中国象棋中,棋子活动的场所,叫做"棋盘",在长方形的平面上,绘有九条平行的竖线和十条平行横线相交组成,共九十个交叉点,棋子就摆在这些交叉点上。中间第五、第六两横线之间未画竖线的空白地带,称为"河界",整个棋盘就以"河界"分为相等的两部分;两方将帅坐镇、画有"米"字方格的地方,叫做"九宫"。
中国象棋中,马是威力很大的棋子。马走动的方法是一直一斜,即先横着或直着走一格,然后再斜着走一个对角线,俗称"马走斜"。马一次可走的选择点可以达到四周的八个点,故有"八面威风"之说。
我们约定最左下角点的坐标为(0,0),则最右上角的坐标为(9, 8)。上图中马在坐标(2, 2)处。它走一步可以到达坐标点(1, 0),(0, 1),(0, 3),(1, 4),(3, 4),(4, 3),(4, 1)或(3,0)。如下图所示。
我们约定当前棋盘上只有一个马,给出起点坐标和终点坐标,求从起点到终点,马最少要走几步?
输入
4个整数,前2个数表示起点坐标,后2个数表示终点坐标。
输出
一个整数,表示从起点到终点最少需要走的步数。
样例输入
2 2 5 2
样例输出
描述
在中国象棋中,棋子活动的场所,叫做"棋盘",在长方形的平面上,绘有九条平行的竖线和十条平行横线相交组成,共九十个交叉点,棋子就摆在这些交叉点上。中间第五、第六两横线之间未画竖线的空白地带,称为"河界",整个棋盘就以"河界"分为相等的两部分;两方将帅坐镇、画有"米"字方格的地方,叫做"九宫"。
中国象棋中,马是威力很大的棋子。马走动的方法是一直一斜,即先横着或直着走一格,然后再斜着走一个对角线,俗称"马走斜"。马一次可走的选择点可以达到四周的八个点,故有"八面威风"之说。
我们约定最左下角点的坐标为(0,0),则最右上角的坐标为(9, 8)。上图中马在坐标(2, 2)处。它走一步可以到达坐标点(1, 0),(0, 1),(0, 3),(1, 4),(3, 4),(4, 3),(4, 1)或(3,0)。如下图所示。
我们约定当前棋盘上只有一个马,给出起点坐标和终点坐标,求从起点到终点,马最少要走几步?
输入
4个整数,前2个数表示起点坐标,后2个数表示终点坐标。
输出
一个整数,表示从起点到终点最少需要走的步数。
样例输入
2 2 5 2
样例输出
3
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int st1,st2,end1,end2;
struct chess
{
int x,y;
int step;
} ;
bool map[15][15];
int bfs()
{
chess a,next;
queue<chess> Q;
a.x=st1;
a.y=st2;
a.step=0;
Q.push(a);
map[st1][st2]=1;
while(!Q.empty())
{
a=Q.front();
if(a.x==end1&&a.y==end2)
return a.step;
Q.pop();
next=a;
next.x=a.x+1; next.y=a.y+2;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x+2; next.y=a.y+1;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x+2; next.y=a.y-1;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x+1; next.y=a.y-2;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x-1; next.y=a.y-2;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x-2; next.y=a.y-1;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x-2; next.y=a.y+1;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
next.x=a.x-1; next.y=a.y+2;
if(next.x>0&&next.x<10&&next.y>0&&next.y<11)
if(!map[next.x][next.y])
{
next.step=a.step+1;
map[next.x][next.y]=1;
Q.push(next);
}
}
}
int main()
{
while(scanf("%d%d%d%d",&st1,&st2,&end2,&end1)!=EOF)
{
int i;
memset(map,0,sizeof(map));
for(int i=0;i<11;i++)
map[i][0]=map[i][11]=1;
for(int i=0;i<12;i++)
map[0][i]=map[10][i]=1;
st1++;st2++;end1++;end2++;
printf("%d\n",bfs());
}
}