您的位置:首页 > 其它

洛谷 马的遍历

2017-07-03 11:41 190 查看
#include <cstdio>

#include <algorithm>

#include <queue>

#include <iostream>

using namespace std;

queue <int> qx; //定义横坐标队列

queue <int> qy; //定义纵坐标队列

int n,m,a[405][405]; //存放步数

int i,j,k,dx,dy,p,q;

const int dir[8][2]={ //状态转移数组==方向向量

    {1,2},

    {1,-2},

    {-1,2},

    {-1,-2},

    {2,1},

    {2,-1},

    {-2,1},

    {-2,-1}

};

void bfs()

{

    while(!qx.empty())

    { //一直循环到队列为空

        dx=qx.front();

        dy=qy.front();

        qx.pop(); //出队

        qy.pop(); //出队

        for(k=0;k<8;k++)

        {

            i=dir[k][0];

            j=dir[k][1];

            if(i+dx>=1 && i+dx<=n && j+dy>=1 && j+dy<=m && !a[i+dx][j+dy])

            { //判断 是 否 越界 或 已经遍历过

                qx.push(i+dx); //入队

                qy.push(j+dy); //入队

                a[i+dx][j+dy]=a[dx][dy]+1; //步数 为 上一次 加1

            }

        } //这个for循环用来把马跳到没有遍历到的地方去

    }

}

int main()

{

    scanf("%d %d %d %d",&n,&m,&p,&q);

    qx.push(p); //横坐标入队

    qy.push(q); //纵坐标入队

    a[p][q]=1; //步数从1开始,方便判断

    bfs(); //广 搜

    for(p=1;p<=n;p++)

    {

        for(q=1;q<=m;q++)

            printf("%-5d",a[p][q]? a[p][q]-1:-1); /*输出 步数 时 要减1;*/

            /* %-md: 输出格式为整形,长度为m(输出 最小 长度) ,

            左 对 齐;可用m表示你的3,4,5,121;*/

        cout<<endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: