Luogu1443 马的遍历【STL通俗BFS】

喜闻乐见当做BFS的STL模板做了

qwq我这样的蒟蒻也就只能发发模板题

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
struct xy{
    int x,y;
}node,top;
int dx[8]={1,1,2,2,-1,-1,-2,-2};
int dy[8]={2,-2,1,-1,2,-2,1,-1};
int a[405][405],n,m;
queue<xy>Q;
void bfs(){
    Q.push(node);
    while(!Q.empty()){
        top=Q.front(); 
        Q.pop();
            for(int i=0;i<8;i++){
                int xx=top.x+dx[i];
                int yy=top.y+dy[i];
                if(xx<1||xx>n||yy<1||yy>m) continue;
                if(a[xx][yy]==-1){
                    node.x=xx;
                    node.y=yy;
                	Q.push(node);
                    a[xx][yy]=a[top.x][top.y]+1;
                }
            }
    }
}
int main(){
    memset(a,-1,sizeof(a));
    scanf("%d%d%d%d",&n,&m,&node.x,&node.y);
    a[node.x][node.y]=0;
    bfs();
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++)
            printf("%-5d",a[i][j]);
        printf("
");
    }
    return 0;
}
不如吃茶去
原文地址:https://www.cnblogs.com/pushinl/p/8946983.html