马的遍历 | 正确题解
2025-09-13 18:01:40
发布于:广东

























#include<bits/stdc++.h>

using namespace std;


int dx[8] = {-2,-1,1,2,2,1,-1,-2};

int dy[8] = {-1,-2,-2,-1,1,2,2,1};

struct stu{



int x,y,step;


}r,l;



bool vis[1010][1010];


int a[1010][1010];


int n,m,sx,sy;


queue<stu> q;


void bfs(){



q.push({sx,sy,0});


vis[sx][sy] = 1;


while(q.size()){


r = q.front();


q.pop();


a[r.x][r.y] = r.step;


for(int i = 0;i < 8;i++){

l.x = r.x + dx[i];


l.y = r.y + dy[i];


if(1 <= l.x && l.x <= n && 1 <= l.y && l.y <= m && vis[l.x][l.y] == 0){
l.step = r.step + 1;

vis[l.x][l.y] = 1;

q.push(l);


}



}



}



}



int main(){



cin>>n>>m>>sx>>sy;

for(int i = 1;i <= n;i++){

for(int j = 1;j <= m;j++){

a[i][j] = -1;


}



}



bfs();



for(int i = 1;i <= n;i++){

for(int j = 1;j <= m;j++){

cout<<a[i][j]<<" ";

}



cout<<endl;


}



return 0;



}




























这里空空如也







有帮助,赞一个