HLG移动

来源:互联网 发布:身份证app扫描软件 编辑:程序博客网 时间:2024/05/18 03:02

在平面坐标系内,有两个坐标轴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


vis【i][j】 == -1 表示没被访问过,bfs模板题


#include <iostream>

#include <queue>
#include <stdio.h>
#include <string.h>


using namespace std;


int vis[400][400];
struct point
{
    int x0;
    int y0;
};


int move[8][2] = {{-2,1}, {2,1}, {-1,2}, {1,2}, {-2,-1}, {2,-1}, {-1,-2}, {1,-2}};


bool check( point now){
    if( (vis[now.x0][now.y0]== -1)
      &&(now.x0>=0&&now.x0<=300&&now.y0>=0&&now.y0<=300) )
    return 1;
    else return 0;
}
void bfs(int x1, int y1,int x2, int y2)
{
    queue<point> que;
    point now,temp;
    now.x0 = x1;
    now.y0 = y1;
    que.push(now);
    vis[now.x0][now.y0] = 0;


    while(!que.empty())
    {
        temp = que.front();
        que.pop();


        for( int i = 0; i<8; i++)
        {
            now.x0 = temp.x0 + move[i][0];
            now.y0 = temp.y0 + move[i][1];


            if(check(now))
            {


                que.push(now);
                vis[now.x0][now.y0] = vis[temp.x0][temp.y0] + 1;
                 if(now.x0 == x2 && now.y0 == y2)
                  return ;
            }
        }
    }


}


int main()
{
    int x1,y1,x2,y2;
    while(scanf("%d%d%d%d", &x1, &y1, &x2, &y2)!= EOF)
    {
       memset(vis,-1,sizeof(vis));
        if(x1 == x2 && y1== y2)
         printf("0\n");
        else
        {


            bfs(x1,y1,x2,y2);
            cout<<vis[x2][y2]<<endl;
         }
    }
    return 0;
}
0 0
原创粉丝点击