40分求助

P1443 马的遍历

cnqing_ze @ 2024-12-08 20:44:00

#include <bits/stdc++.h>
using namespace std;
vector<vector<int>>s;
vector<vector<bool>>p;
int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int dy[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int N,M,X,Y;
int n=0;
void bfs(int x,int y) {
    queue<vector<int>> q;
    q.push({x,y,0});
    p[y][x]=true;
    while (!q.empty())
    {
        s[q.front()[1]][q.front()[0]]=q.front()[2];
    for(int i=0;i<8;i++){
        int x_=q.front()[0]+dx[i];
        int y_=q.front()[1]+dy[i];
        if(x_<0||x_>=M||y_<0||y_>=N||p[y_][x_]) continue;
        q.push({x_,y_,q.front()[2]+1});
        p[y_][x_]=true;
    }   
        q.pop();
    }
    return;
}
int main() {
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin>>N>>M>>X>>Y;
    s.resize(N,vector<int>(M,-1));
    p.resize(N,vector<bool>(M,false));
    bfs(X-1,Y-1);
    for(int y=0;y<N;y++){
        for (int x=0;x<M;x++)
            cout << s[y][x]<<(x==M-1? "\n":" ");
    }
    return 0;
}

|