HLG 1181 移动

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct point
{
    int x, y;
};

point _xy_(int p, int q)
{
    point m;
    m.x = p;
    m.y = q;
    return m;
}

bool used[301][301];//定义数组记录所走的点
int BFS(point a, point b)
{
    memset(used, false, sizeof(used));
    int s = 0;
    queue<point>m;
    m.push(a);
    used[a.x][a.y]=true;
    while(true)
    {
        int temp = m.size();
        while(temp--)
        {
            point head = m.front();
            if(head.x == b.x && head.y == b.y)
            {
                return s;//当遇到符合条件的点就返回所走的层数  
            }
            if((head.x-1>=0&&head.y+2<=300)&&!used[head.x-1][head.y+2])
            {
                m.push(_xy_(head.x-1, head.y+2));
                used[head.x-1][head.y+2] = true;
            }
            if((head.x-2>=0&&head.y+1<=300)&&!used[head.x-2][head.y+1])
            {
                m.push(_xy_(head.x-2, head.y+1));
                used[head.x-2][head.y+1] = true;
            }
            if((head.x+1<=300&&head.y+2<=300)&&!used[head.x+1][head.y+2])
            {
                m.push(_xy_(head.x+1, head.y+2));
                used[head.x+1][head.y+2] = true;
            }
            if((head.x+2<=300&&head.y+1<=300)&&!used[head.x+2][head.y+1])
            {
                m.push(_xy_(head.x+2, head.y+1));
                used[head.x+2][head.y+1] = true;
            }
            if((head.x-1>=0&&head.y-2>=0)&&!used[head.x-1][head.y-2])
            {
                m.push(_xy_(head.x-1, head.y-2));
                used[head.x-1][head.y-2] = true;
            }
            if((head.x-2>=0&&head.y-1>=0)&&!used[head.x-2][head.y-1])
            {
                m.push(_xy_(head.x-2, head.y-1));
                used[head.x-2][head.y-1] = true;
            }
            if((head.x+1<=300&&head.y-2>=0)&&!used[head.x+1][head.y-2])
            {
                m.push(_xy_(head.x+1, head.y-2));
                used[head.x+1][head.y-2] = true;
            }
            if((head.x+2<=300&&head.y-1>=0)&&!used[head.x+2][head.y-1])
            {
                m.push(_xy_(head.x+2, head.y-1));
                used[head.x+2][head.y-1] = true;
            }
            m.pop();
        }
        s++; /*以上为分别能走的八个方向,每走一个方向就重定义一个head,head代表当前位置             广搜是搜树的每层,每搜到一个符合条件的值就入队,搜完一层就s++,然后把上一层的             元素出队*/ 
    }
}
int main()
{
    point p1, p2;
    while(cin >> p1.x >>p1.y >>p2.x >>p2.y)
    {
        cout << BFS(p1, p2) << endl;
    }
     return 0;
}


 

你可能感兴趣的:(ACM)