移动
在平面坐标系内,有两个坐标轴x轴和y轴。(x,y)表示点的坐标。
有一点处于(x1,y1)位置上,他可以向相临8个位置移动(移动方式见下图)。
划定范围:此点只可以在[0<=x<=300,0<=y<=300]范围内移动。
要求:给出起始位置(x1,y1)和目标位置(x2,y2),要求同学求出从起始位置移动到目标位置所需的最少次数。
Input
输入包括多组测试用例。
对于每组测试用例,包含4个正整数,x1,y1,x2,y2,范围均为[0,300]。
Output
输出移动所需的最少次数。
Sample Input
0 0 1 2
0 0 2 1
Sample Output
1
1
题目链接:
acm.hrbust.edu.cn/index.php?m…
解题思路:
看到是个300的图,首先就想起了广搜,然后把8个方向写出来,模板就行
程序代码:
#include<stdio.h>
#include<string.h>
using namespace std;
#include<queue>
int x1,y1,x2,y2;
bool book[310][310];
struct data{
int x;
int y;
int step;
};
int bfs();
int main()
{
int i,j;
while(scanf("%d%d%d%d",&x1,&y1,&x2,&y2)!=EOF)
{
memset(book,0,sizeof(book));
printf("%d\n",bfs());
}
return 0;
}
int bfs()
{
int i;
int next[8][2]={2,1,1,2,-1,2,-2,1,-2,-1,-1,-2,1,-2,2,-1};
data A,B;
queue<data>q;
A.x=x1;
A.y=y1;
A.step=0;
q.push(A);
book[A.x][A.y]=1;
while(!q.empty())
{
A=q.front();
q.pop();
if(A.x==x2&&A.y==y2)
return A.step;
for(i=0;i<8;i++)
{
B.x=A.x+next[i][0];
B.y=A.y+next[i][1];
B.step=A.step+1;
if(B.x<0||B.x>300||B.y<0||B.y>300||book[B.x][B.y])
continue;
q.push(B);
book[B.x][B.y]=1;
}
}
}