洛谷P1443 马的遍历

https://www.luogu.org/problem/P1443

#include<bits/stdc++.h>
using namespace std;
queue<int> qx,qy,qstep;
int n,m,X,Y,a[500][500];
bool vis[500][500];
int xx[9]= {0,-1,-2,-2,-1,1,2,2,1};
int yy[9]= {0,-2,-1,1,2,2,1,-1,-2};
void Print(int x) {   //对齐
    int Ws=0;
    if(x==0) printf("    ");//特判,0占一位
    else {
        while(x>0) {
            ++Ws;// 位数+1
            x/=10;// x/=10 相当于将x的最后一位删除
        }
        for(int S=1; S<=5-Ws; ++S) //向左对齐,输出 5-位数 个空格
            printf(" ");
    }
}
void bfs() {
    int x,y,step;
    while(qx.empty()==0) {
        x=qx.front();//返回 qx 第一个元素的值
        y=qy.front();//返回 qy 第一个元素的值
        step=qstep.front();//返回 qstep 第一个元素的值
        a[x][y]=step;
        qx.pop();
        qy.pop();
        qstep.pop();
        for(int i=1; i<=8; ++i) {
            if(x+xx[i]>=1 && x+xx[i]<=n && y+yy[i]>=1 && y+yy[i]<=m && vis[x+xx[i]][y+yy[i]]==0) {
                vis[x+xx[i]][y+yy[i]]=1;//该点被访问
                qx.push(x+xx[i]);//压入新的 x 坐标
                qy.push(y+yy[i]);//压入新的 y 坐标
                qstep.push(step+1);//走到该点又要一步
            }
        }
    }
}
int main() {
    scanf("%d%d%d%d",&n,&m,&X,&Y);//读入
    qx.push(X);//将初始位置 x 坐标压入队列
    qy.push(Y);//将初始位置 y 坐标压入队列
    qstep.push(0);//初始位置只要走 0 步
    vis[X][Y]=1;//坑点,要将初始位置设为走过,否则会出现回跳现象
    bfs();//将任务交给广搜
    for(int i=1; i<=n; ++i) {
        for(int j=1; j<=m; ++j)
            if(!vis[i][j]) printf("-1   ");//若该点未走到过,则输出 -1 以及3个空格
            else {
                printf("%d",a[i][j]);//输出那个数
                Print(a[i][j]);//输出对应的空格数
            }
        printf("
");//回车
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/11766227.html