哈理工oj1181

 #include<iostream>
 #include<string.h>
 using namespace std;

struct node
{
    int x;//点的坐标
    int y;
    int s;//记录步数
};

int main()
{
    int startx,starty;
    int endx,endy;
    int tx,ty;
    int n,m;
    int k;
    node que[300000];
    int book[500][500];
    int head,tail;
    int next[8][2]={{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1}};
    //方向
    while(cin>>startx>>starty>>endx>>endy)
    {
        if(startx==endx&&starty==endy)
        {
            cout<<"0"<<endl;
        }
        else
            {
            int flag=0;
            memset(book,0,sizeof(book));//初始全未被标记过
            head=1;
            tail=1;
            //起止点入队列
            que[tail].x=startx;
            que[tail].y=starty;
            que[tail].s=0;
            book[startx][starty]=1;
            tail++;
            //BFS
            while(head<tail)
            {
                for(k=0;k<8;k++)//遍历8个方向
                {
                    tx=que[head].x+next[k][0];
                    ty=que[head].y+next[k][1];
                    //是否超出范围
                    if(tx<0||tx>300||ty<0||ty>300)
                    {
                        continue;
                    }
                    //未被访问过
                    if(book[tx][ty]==0)
                    {
                        book[tx][ty]=1;
                        //入队列
                        que[tail].x=tx;
                        que[tail].y=ty;
                        que[tail].s=que[head].s+1;
                        tail++;
                        if(tx==endx&&ty==endy)//到达访问的点结束
                        {
                            flag=1;
                            break;
                        }
                    }
                }
                if(flag==1)
                {
                    break;//结束循环
                }
                head++;
            }
            cout<<que[tail-1].s<<endl;
            }
    }
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值