pooh_mukuigumeng13 @ 2024-11-23 16:23:42
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<iomanip>
using namespace std;
int dx[8]={1,2,2,1,-1,-2,-2,-1};
int dy[8]={2,1,-1,-2,-2,-1,1,2};
int front=0,tail=0;
struct cz{
int cs;
bool visi;
}a[405][405];
struct qu{
int h;
int l;
}q[10005];
int main(){
int l,h,x,y;
cin>>l>>h>>x>>y;
for (int i=1;i<=h;i++){
for(int j=1;j<=l;j++){
a[i][j].visi=1;
a[i][j].cs=0;
}
}
q[++tail].h=x;
q[tail].l=y;
a[x][y].visi=0;
while(front<tail){
front++;
x=q[front].h;
y=q[front].l;
for (int i=0;i<=7;i++){
int x1=x+dx[i];
int y1=y+dy[i];
if(a[x1][y1].visi){
q[++tail].h=x1;
q[tail].l=y1;
a[x1][y1].visi=0;
a[x1][y1].cs=tail;
}
}
}
for (int i=1;i<=l;i++){
for (int j=1;j<=h;j++){
if (a[i][j].visi)
cout<<-1;
else
cout<<a[i][j].cs<<'\n';
}
}
return 0;
}
by cuiencheng @ 2024-11-23 17:01:44
#include <bits/stdc++.h>
using namespace std;
int n,m,x,y;
int k[410][410];
int f[9] = {0,1,2,2,1,-1,-2,-2,-1};//x
int h[9] = {0,-2,-1,1,2,2,1,-1,-2};//y
struct node{
int a;//位置,=x,y
int b;
int step;//步数
};
queue<node> q;
void BFS(int x,int y,int s){
node t={x,y,s};
q.push(t);
while(q.size() > 0){
int cq ;
cq = q.front().a;
int cq_1;
cq_1 = q.front().b;
int cq_step;
cq_step = q.front().step;
q.pop();
for(int i = 1;i <= 8;i++){
int v_1 = cq+f[i];
int v_2 = cq_1+h[i];
if(v_1 >= 1&&v_1 <= n&&k[v_1][v_2] == 0&&v_2>=1&&v_2 <= m){
q.push({v_1 , v_2 , cq_step+1});
k[v_1][v_2] = cq_step+1;
}
}
}
}
int main(){
cin >>n>>m>>x>>y;
k[x][y] = 0;
BFS(x,y,0);
for(int i = 1;i <= n;i++){
for(int j = 1;j <= m;j++){
if(i == x&&j == y){
cout <<0<<" ";
continue;
}
if(k[i][j] == 0){
cout <<-1<<" ";
continue;
}
cout <<k[i][j] <<" ";
}
cout <<endl;
}
return 0;
}