30分蒟蒻求助
查看原帖
30分蒟蒻求助
1034276
lz081101楼主2023/7/7 21:47
#include <iostream>
#include <queue>

using namespace std;

int x,y,m,n;
int dx[8]={-1,-1,1,1,-2,2,-2,2};
int dy[8]={-2,2,-2,2,1,1,-1,-1};

struct node{
    int x,y,steps;
};

node a;
queue <node> q;
int board[400][400];

void BFS(){
    while(!q.empty()){
        node t=q.front();
        board[t.x][t.y]=t.steps;
        for(int i=0;i<8;i++){
            int x1=t.x+dx[i],y1=t.y+dy[i];
            if(x1>=0&&x1<n&&y1>=0&&y1<m&&board[x1][y1]==-1){
                a.x=x1;
                a.y=y1;
                a.steps=t.steps+1;
                q.push(a);
            }
        }
        q.pop();
    }
    return;
}

int main()
{
    for(int i=0;i<400;i++){
        for(int j=0;j<400;j++){
            board[i][j]=-1;
        }
    }
    cin>>n>>m>>x>>y;
    a.x=x-1;a.y=y-1;a.steps=0;
    q.push(a);
    BFS();
    for(int i=0;i<n;i++){
        for(int j=0;j<m;j++){
            cout<<board[i][j]<<"  ";
        }
        cout<<endl;
    }
    return 0;
}
2023/7/7 21:47
加载中...